package com.zoweunion.mechanic.service.app.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.TSSsVehicleBrandParentDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.app.WeatherMapper;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.dao.base.VehicleDataMapper;
import com.zoweunion.mechanic.entity.FaultCodeBean;
import com.zoweunion.mechanic.entity.RenewalCardEntity;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.things.StartAndEndTimeData;
import com.zoweunion.mechanic.model.things.ThingsData;
import com.zoweunion.mechanic.service.app.ThingsDataService;
import com.zoweunion.mechanic.service.app.ToolCarDataService;
import com.zoweunion.mechanic.service.app.ToolViewBoardService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.cache.ThingsCacheUtil;
import com.zoweunion.mechanic.util.common.CarDataMocha;
import com.zoweunion.mechanic.util.common.CarDataStatisticsUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import com.zoweunion.mechanic.util.hefeng.HeFengWeather;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Random;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Service
public class ToolCarDataServiceImpl extends BaseService implements ToolCarDataService {
    /** 油位 */
    private final String FuelGauge = "FuelGauge";
    /** 运行时长 */
    private final String OperatingHours = "OperatingHours";
    @Autowired
    private ToolCarDataMapper toolCarDataMapper;
    @Autowired
    private AddressGEOUtil addressGEOUtil;
    @Autowired
    private CarDataMocha carDataMocha;
    @Autowired
    private ThingsCacheUtil thingsCacheUtil;
    @Autowired
    private ThingsDataService thingsDataService;
    @Autowired
    private HeFengWeather heFengWeather;
    @Autowired
    private WeatherMapper weatherMapper;
    @Resource(name = "cachedThreadPool")
    private ExecutorService cachedThreadPool;
    @Autowired
    private Environment env;
    @Autowired
    private ToolCarDataServiceImpl toolCarDataServiceImpl;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderServicelmpl orderServicelmpl;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ToolViewBoardService toolViewBoardService;

    @Autowired
    private VehicleDataMapper vehicleDataMapper;

    @Resource(name = "cachedThreadPool")
    private ExecutorService executorService;

    @Autowired
    private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;

    @Autowired
    private OwnerDao ownerDao;

    @Autowired
    private TSSsVehicleBrandParentDao tsssVehicleBrandParentDao;



    @Override
    public LinkedHashMap<String,List<Map<String, Object>>> selectTrackHistoryLastNew(Map<String, Object> map) throws ParseException {
        List<Map<String, Object>> objects = new ArrayList<>();
        String thingsId = Orgin.getString(map,"thingsId");
        //startTime endTime
        Date dateStart = Orgin.getDate(map,"startTime");
        Date dateEnd = Orgin.getDate(map,"endTime");
        List<String> dateList=DateUtils.getDays(DateUtils.localFormater.format(dateStart), DateUtils.localFormater.format(dateEnd));

        if(CollUtil.isNotEmpty(dateList)) {
            for (String strDate : dateList) {
                if (!Constants.is18Or19(thingsId)){
                    return null;
                }

                String dateString = strDate;
                Date date=DateUtils.localFormater.parse(strDate);

                int type = Orgin.getIntValue(map,"type");//1行驶,2停车
                //查询当天轨迹段
                Map<String,Object> workHourJson = this.workingHoursDistributionStatistics("",thingsId,dateString);
                List<String> startTime = JSON.parseObject(workHourJson.get("startTimeList").toString(), List.class);
                List<String> endTime = JSON.parseObject(workHourJson.get("endTimeList").toString(), List.class);
                if (startTime.size()==endTime.size()&&startTime.size()!=0){
                    List<Map<String, Object>> listS = this.getList(startTime, date, thingsId);
                    List<Map<String, Object>> listE = this.getList(endTime, date, thingsId);
                    if (startTime.size()!=listS.size()){
                        return null;
                    }
                    if (type==1){
                        for(int i =0;i<listS.size();i++){
                            Map<String, Object> listMap = new HashMap<>();
                            listMap.put("startTime",listS.get(i).get("sample_time"));
                            listMap.put("locationS",listS.get(i).get("location"));
                            listMap.put("addressS",listS.get(i).get("address"));
                            listMap.put("endTime",listE.get(i).get("sample_time"));
                            listMap.put("locationE",listE.get(i).get("location"));
                            listMap.put("addressE",listE.get(i).get("address"));
                            objects.add(listMap);
                        };
                    }
                   if (type==2){//如果是停车 进行拼接
                        for(int i =0;i<listS.size()-1;i++){
                            Map<String, Object> listMap = new HashMap<>();
                            listMap.put("startTime",listE.get(i).get("sample_time"));
                            listMap.put("locationS",listE.get(i).get("location"));
                            listMap.put("addressS",listE.get(i).get("address"));
                            listMap.put("endTime",listS.get(i+1).get("sample_time"));
                            listMap.put("locationE",listS.get(i+1).get("location"));
                            listMap.put("addressE",listS.get(i+1).get("address"));
                           Float tractTime = Float.valueOf(startTime.get(i+1)) -Float.valueOf(endTime.get(i));
                            listMap.put("tractTime", Math.floor(tractTime)+"小时"+Math.floor(tractTime%1*60)+"分钟");
                            objects.add(listMap);
                        };
                   }
                }
            }
        }

        //if (new Date().before(date)){
        //return objects;
        //}
        LinkedHashMap<String,List<Map<String, Object>>> maplastData=new LinkedHashMap<>();
        List<Map<String, Object>> objectsNew = null;
        if(CollUtil.isNotEmpty(objects)){
            for (Map<String, Object> mapNew:objects) {
                String startTimekey=(String)mapNew.get("startTime");
                String startTimekeyLast=DateUtils.localFormater.format(DateUtils.localFormater.parse(startTimekey));
                List<Map<String, Object>>  dataList=maplastData.get(startTimekeyLast);
                if(CollUtil.isNotEmpty(dataList)){
                    dataList.add(mapNew);
                    maplastData.put(startTimekeyLast,dataList);
                }else{
                    objectsNew = new ArrayList<Map<String, Object>>();
                    objectsNew.add(mapNew);
                    maplastData.put(startTimekeyLast,objectsNew);
                }
            }
        }
        return maplastData;
    }


    @Deprecated
    @Override
    public List<Map<String, Object>> list(User currentUser, Map<String, Object> reqMap) {

        List<Map<String, Object>> carList;
        if (!isGuest(currentUser)) {
            // 设置分页
            if (reqMap.get("currentPage") != null && StringUtils.isNotBlank(reqMap.get("currentPage").toString())) {
                this.appPage(reqMap);
            }

            reqMap.put("sId", currentUser.getS_id());
            reqMap.put("roleId", currentUser.getR_id());
            reqMap.put("userId", currentUser.getId());

            if (isSuperAdmin(currentUser.getUser_account())) {
                reqMap.put("superAdmin", true);
                carList = toolCarDataMapper.listCar(reqMap);
            } else if (Constants.ROLE_CZ.equals(currentUser.getR_id()) || Constants.ROLE_SJ.equals(currentUser.getR_id())) {
                carList = toolCarDataMapper.listOwnerCar(reqMap);
            } else if (Constants.ROLE_GLY.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id())) {
                carList = toolCarDataMapper.listCar(reqMap);
            } else {
                carList = Collections.emptyList();
            }
        } else {
            // 设置分页
            if (reqMap.get("currentPage") != null && StringUtils.isNotBlank(reqMap.get("currentPage").toString())) {
                this.appPage(reqMap);
            }
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            carList = toolCarDataMapper.listGuestCar(reqMap);
        }

        // 设置状态
        return this.setState(carList);
    }

    /**
     * 设置经纬度
     * @param carList
     */
    @Override
    public List<Map<String, Object>> setState(List<Map<String, Object>> carList) {
        List<Map<String, Object>> returnCarList = new ArrayList<>(carList);
        for (Map<String, Object> carMap : carList) {
            // adviceState 1-工作中 2-已关机 3-暂无位置信息 4-未配置物联网关
            if (carMap.get("device_template") == null) {
                carMap.put("adviceState", "未配置物联网关");
                returnCarList.remove(carMap);
                continue;
            }
            String tableName = ThingsData.getTableName(carMap.get("device_template").toString());
            // 获取车辆最新设备信息
            Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, carMap.get("things_id").toString());
            Map<String, Object> realDataMap = new HashMap<>();
            realDataMap.put("thingsId",carMap.get("things_id").toString());
            realDataMap.put("date",LocalDate.now());
            realDataMap.put("realData",true);
            // 获取无偏差经纬度
            Map<String, Object> locationMap = toolCarDataMapper.getCarRealData(realDataMap);

            // 查询故障代码
            Integer faultCount = toolCarDataMapper.countRealFaultCodeDataToday(carMap.get("things_id").toString());

            if (faultCount == null) { faultCount = 0;};

            if (carDataMap != null) {
                carDataMap.put("faultCount", faultCount);
            }

            if (locationMap != null && carDataMap != null && locationMap.get(Constants.THINGS_GPSlongitude) != null) {
                carDataMap.put(Constants.THINGS_GPSlatitude, locationMap.get(Constants.THINGS_GPSlatitude));
                carDataMap.put(Constants.THINGS_GPSlongitude, locationMap.get(Constants.THINGS_GPSlongitude));
            } else {
                carMap.put("adviceState", "暂无位置信息");
                carMap.put(Constants.THINGS_GPSlatitude, "");
                carMap.put(Constants.THINGS_GPSlongitude, "");
                // 设置经纬度
                // carMap.put("GPSlongitude", 120);
                // carMap.put("GPSlatitude", 32);
                // carMap.put("GPSlongitude", 120.30);
                // carMap.put("GPSlatitude", 31.57);
                returnCarList.remove(carMap);
                continue;
            }

            // 设置经纬度
            double[] gps = GPSUtil.gps84_To_Gcj02(new BigDecimal(carDataMap.get(Constants.THINGS_GPSlatitude).toString()).doubleValue(),
                    new BigDecimal(carDataMap.get(Constants.THINGS_GPSlongitude).toString()).doubleValue());
            carMap.put(Constants.THINGS_GPSlongitude, gps[1]);
            carMap.put(Constants.THINGS_GPSlatitude, gps[0]);

            LocalDateTime sampleTime = DateUtil.formatTimestampToTime((Timestamp) carDataMap.get("sample_time"));
            Duration duration = Duration.between(sampleTime, LocalDateTime.now());
            boolean hasFaultCode = false;
            if (carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + "1") != null) {
                hasFaultCode = true;
            }
            carMap.put("hasFaultCode", hasFaultCode);

            // 如果是卡特的设备
            if (carDataMap.containsKey(Constants.THINGS_IsCAT)) {

                if (carDataMap.containsKey("OperatingHours")) {

                    Double operatingHours = Double.parseDouble(carDataMap.get("OperatingHours").toString());

                    if (operatingHours > 0) {

                        carMap.put("adviceState", "工作中");
                        this.wrapSetAdviceState(duration, carMap, carDataMap, hasFaultCode);
                    }else {

                        carMap.put("adviceState", "已关机");
                    }
                }

            } else if (carDataMap.containsKey(Constants.THINGS_Ignition)) {

                if (carDataMap.get(Constants.THINGS_Ignition) != null) {

                    double ignition = Double.valueOf(carDataMap.get(Constants.THINGS_Ignition).toString());
                    double rotateSpeed = Double.valueOf(carDataMap.get(Constants.THINGS_RotateSpeed).toString());

                    if (ignition > 10) {
                        this.wrapSetAdviceState(duration, carMap, carDataMap, hasFaultCode);
                    } else {

                        if (rotateSpeed > 0) {

                            this.wrapSetAdviceState(duration, carMap, carDataMap, hasFaultCode);
                        } else {

                            carMap.put("adviceState", "已关机");
                        }
                    }
                }else {

                    this.wrapSetAdviceState(duration, carMap, carDataMap, hasFaultCode);
                }

            } else {
                this.wrapSetAdviceState(duration, carMap, carDataMap, hasFaultCode);
            }
            if (Constants.THINGS_ID_GUEST.equals(carMap.get("things_id").toString())) {
                carMap.put("adviceState", "工作中");
            }
            if (carMap.get("running") != null && carMap.get(Constants.THINGS_OperatingHours) != null){
                double running = new BigDecimal(carMap.get("running").toString())
                        .add(new BigDecimal(carMap.get(Constants.THINGS_OperatingHours).toString())).doubleValue();
                carMap.put("running", running);
            }

            // 显示卫星数据页面
            if (carDataMap.containsKey("GP_NUM")) {

                carMap.put("GPSsatellite",true);
            }else {

                carMap.put("GPSsatellite",false);
            }
        }
        return returnCarList;
    }

    private void wrapSetAdviceState(Duration duration, Map<String, Object> carMap, Map<String, Object> carDataMap, boolean hasFaultCode) {
        if (duration.toMinutes() > 5) {
            carMap.put("adviceState", "已关机");
        } else {

            carMap.put("adviceState", "工作中");
            this.wrapSetAdviceStateFault(hasFaultCode, carDataMap, carMap);
        }
    }

    @Override
    public Map<String, Object> carOilLevelStatisticsNew(Map<String, Object> params) {
        String thingsId = Orgin.getString(params, "thingsId");
        List<Map<String, Object>> maps = orderDao.selectFuelDetail(params);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("dataList", maps);
        int fuelTanks = this.getFuelTanks(orderDao.getFuelGauge(thingsId));
        if (fuelTanks==0){
            map1.put("fuelTank", 300);
        }else {
            map1.put("fuelTank", fuelTanks);
        }
        return map1;
    }


    /**
     * 获取油箱容量
     *
     * @return
     */
    public int getFuelTanks(Object tankCapacity) {
        //  获取油箱容量
        if (tankCapacity == null) {
            return 300;
        }
        return Integer.valueOf((String) tankCapacity);
    }

    @Override
    public Map<String, Object> carCountFuelWork(Map<String, Object> map) {
        Date startTime = Orgin.getDate(map, "startTime");
        Date endTime = Orgin.getDate(map, "endTime");
        String thingsId = Orgin.getString(map, "thingsId");
        List<String> ymd = orderServicelmpl.createYMD(startTime, endTime);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        Map<String, Object> hashMap = new LinkedHashMap<>();
        hashMap.put("workSum","");
        hashMap.put("fuelSum","");
        hashMap.put("dataList","");

        ymd.forEach(item-> {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("date", item);
            map1.put("workHour", "");
            map1.put("fuel", "");
            Map<String, Object> mapCount = toolCarDataMapper.carCountFuelWork(item, thingsId);
            if (mapCount!=null){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String nowDate = simpleDateFormat.format(new Date());
                if (item.equals(nowDate)){
                    //如果是当天 获取当日工时
                    map1 = this.getWorkHour(thingsId, map1);
                    //获取当日消耗燃油
                    map1 = this.getFuelConsumption(thingsId, map1,hashMap);
                }else {
                    if(Double.valueOf(Orgin.getString(mapCount,"work_hours"))<24){
                        map1.put("workHour",mapCount.get("work_hours"));
                    }else {
                        map1.put("workHour","24");
                    }
                    double consumption = Orgin.getDoubleValue(mapCount, "fuel_consumption");
                    if (consumption <0){
                        consumption=-consumption;
                    }
                    map1.put("fuel",consumption);
                }
            }else {
                map1.put("workHour","0");
                map1.put("fuel","0");
            }
            arrayList.add(map1);
        });
        if (arrayList.size()!=0){
            double sum = arrayList.stream().collect(Collectors.summingDouble(x -> (Double.valueOf( x.get("workHour").toString()))));
            sum=sum-Double.valueOf(arrayList.get(arrayList.size()-1).get("workHour").toString());
            BigDecimal bg12 = new BigDecimal(sum);
            double f1 = bg12.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            hashMap.put("workSum",f1+"h");
            double fuelSum = arrayList.stream().collect(Collectors.summingDouble(x -> (Double.valueOf( x.get("fuel").toString()))));
            BigDecimal bg1 = new BigDecimal(fuelSum);
            double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            hashMap.put("fuelSum",f2+"L");
        }
        hashMap.put("dataList",arrayList);
        return hashMap;
    }

    public Map<String, Object> getFuelConsumption(String thingsId, Map<String, Object> map1,Map<String, Object> map2) {
        String tableName = this.selectTableByThingsId(thingsId);
        //查询数据
        double fuelConsumption = toolCarDataMapper.getFuelConsumption(thingsId, tableName + "_tb1");
        if (fuelConsumption==0){

            if (toolCarDataMapper.selectEveryDayFuel(thingsId) == null) {

                fuelConsumption = 0;
            }else {
                //查询计算油耗
                fuelConsumption=toolCarDataMapper.selectEveryDayFuel(thingsId);
            }
        }
        map1.put("fuel",fuelConsumption);
        return map1;
    }

    @Override
    public Map<String, Object> realData(User currentUser, Map<String, Object> reqMap) throws MyException {
        /*if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            return carDataMocha.getRealData();
        } else {
            reqMap.put("sId", currentUser.getS_id());
        }*/

        String thingsId = reqMap.get("thingsId").toString();
        if (thingsId.equals(Constants.THINGS_ID_GUEST)) {
            return carDataMocha.getRealData();
        }

        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
        if (pcCarMap == null || pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备未配置网关");
        }
        String adviceTemplateId = pcCarMap.get("device_template").toString();
        String tableName = ThingsData.getTableName(adviceTemplateId);
        // 获取智能模版参数
        LinkedList<Map<String, Object>> intelligentTemplateDetails = thingsCacheUtil.getIntelligentTemplateDetails(adviceTemplateId);
        List<String> tags = intelligentTemplateDetails.stream().map(map -> map.get("tag").toString()).collect(Collectors.toList());
        CarDataStatisticsUtil.setSampleTimeTag(intelligentTemplateDetails);
        boolean hasIgnition = false;
        if (tags.contains(Constants.THINGS_Ignition)) {
            hasIgnition = true;
        }

        boolean validRotateSpeed = false;
        if (tags.contains(Constants.THINGS_ValidRotateSpeed)) {
            validRotateSpeed = true;
        }

        Map<String,Object> tempMap = new HashMap<>();

        tempMap.put("hasIgnition",hasIgnition);
        tempMap.put("validRotateSpeed",validRotateSpeed);

        // 获取车辆最新设备信息
        Map<String, Object> carDataMap = toolCarDataMapper.lastCarDataIgnition(tableName, thingsId,tempMap);

        if (carDataMap == null) {

            tempMap.put("hasIgnition",false);
            tempMap.put("validRotateSpeed",false);
            carDataMap = toolCarDataMapper.lastCarDataIgnition(tableName, thingsId, tempMap);
        }

        // 查询故障代码
        Integer faultCount = toolCarDataMapper.countRealFaultCodeDataToday(thingsId);

        if (faultCount == null) { faultCount = 0;}

        if (carDataMap != null) {

            carDataMap.put("faultCount",faultCount);
        }

        Map<String, Object> realDataMap = new HashMap<>();
        realDataMap.put("thingsId",thingsId);
        realDataMap.put("date",LocalDate.now());
        realDataMap.put("realData",true);
        // 获取无偏差经纬度
        Map<String, Object> locationMap = toolCarDataMapper.getCarRealData(realDataMap);

        Map<String, Object> laseLocationMap = toolCarDataMapper.getLocationRealData(realDataMap);

        if (laseLocationMap != null && laseLocationMap.get(Constants.THINGS_GPSlongitude) != null) {
            carDataMap.put(Constants.THINGS_GPSlatitude, laseLocationMap.get(Constants.THINGS_GPSlatitude));
            carDataMap.put(Constants.THINGS_GPSlongitude, laseLocationMap.get(Constants.THINGS_GPSlongitude));
        }

        int size = (int)(intelligentTemplateDetails.size() / 0.7);
        // 定义存放变量的map
        Map<String, Object> variableMap = new LinkedHashMap<>(size);
        Map<String, Object> dataMap = new LinkedHashMap<>(size);
        Map<String, Object> mapDataMap = new LinkedHashMap<>(size);

        if (carDataMap == null) {
            mapDataMap.put("CurrentOilLevel", "0%");
//            mapDataMap.put("Address", "");
            mapDataMap.put("CSQ", "0dBm");
            mapDataMap.put("BatVol", "0V");
            mapDataMap.put("OperatingHours", "0h");
        }

        // 设置设备状态
        this.setAdviceState(mapDataMap, carDataMap, tableName, thingsId);

        String sampleTime = null;
        // 封装数据
        for (Map<String, Object> detail : intelligentTemplateDetails ) {
            // 判断字段是否要显示
            if (detail.get("display") != null && "1".equals(detail.get("display").toString())) {
                continue;
            }
            String tag = detail.get("tag").toString();
            String tagValue = "";
            String unit = detail.get("company").toString();
            tag = CarDataStatisticsUtil.formatTag(tag);
            if (carDataMap == null) {
                tagValue = "";
            } else if (carDataMap.get(tag) != null) {
                tagValue = carDataMap.get(tag).toString();
                switch (tag) {
                    case "sample_time":
                        tagValue = DateUtil.formatTimestamp(((Timestamp) carDataMap.get(tag)));
                        sampleTime = tagValue;
                        break;
                    case Constants.THINGS_FuelGauge:
                        double fuelGaugeRadio = Double.valueOf(StringUtils.isBlank(tagValue) ? "0" : tagValue);

                        if (fuelGaugeRadio < 0) {
                            fuelGaugeRadio = 0;
                        } else if (fuelGaugeRadio > 100) {
                            fuelGaugeRadio = 100;
                        }

                        // 获取油箱容量
                        mapDataMap.put("CurrentOilLevel", (int) fuelGaugeRadio + unit);
                        // 如果等于零的话，找到不等于零的数据
                        if (fuelGaugeRadio == 0) {

                            if (tags.contains("FuelGauge")) {

                                String fuelGauge = toolCarDataMapper.getFuelGaugeRadio(tableName, thingsId);

                                double fuelGauge_radio = Double.valueOf(StringUtils.isBlank(fuelGauge) ? "0" : fuelGauge);

                                if (fuelGauge_radio < 0) {
                                    fuelGauge_radio = 0;
                                } else if (fuelGauge_radio > 100) {
                                    fuelGauge_radio = 100;
                                }

                                // 获取油箱容量
                                mapDataMap.put("CurrentOilLevel", (int) fuelGauge_radio + unit);
                            }
                        }

                        break;
                    case Constants.THINGS_GPSlongitude:
                        // 根据经纬度解析出地址
                        String lon = carDataMap.get("GPSlongitude").toString();
                        String lat = carDataMap.get("GPSlatitude").toString();
                        double[] gps = GPSUtil.gps84_To_Gcj02(new BigDecimal(lat).doubleValue(), new BigDecimal(lon).doubleValue());
                        dataMap.put("GPSlongitude", String.format("%.5f", gps[1]) + unit);
                        dataMap.put("GPSlatitude", String.format("%.5f", gps[0]) + unit);
                        mapDataMap.put("GPSlongitude", String.format("%.5f", gps[1]));
                        mapDataMap.put("GPSlatitude", String.format("%.5f", gps[0]));
                        break;
                    case Constants.THINGS_CSQ:
                    case Constants.THINGS_BatVol:
                        // 电压
                        // 信号强度
                        mapDataMap.put(tag, tagValue + unit);
                        break;
                    case Constants.THINGS_OperatingHours:
                        if (DateUtil.parseDate(sampleTime.substring(0, 10)).isBefore(LocalDate.now())) {
                            mapDataMap.put(tag, "0" + unit);
                        } else {

                            Map<String, Object> hoursMap = toolCarDataMapper.getTodayWorkHours(thingsId,tableName);

                            if (hoursMap != null) {

                                String maxHours = hoursMap.get("maxHours").toString();
                                String minHours = hoursMap.get("minHours").toString();

                                mapDataMap.put(tag, (String.format("%.2f", Double.parseDouble(maxHours)-Double.parseDouble(minHours))) + unit);

                            }else {

                                // 今日时长
                                // 获取车辆今日最开始的一条设备信息
                                String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);
                                if (workHoursJson == null) {
                                    mapDataMap.put(tag, "0" + unit);
                                } else {
                                    HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                                    mapDataMap.put(tag, workHoursMap.get("workHours") + unit);
                                }
                            }

                            if (detail.get("name").equals("运行小时")) {

                                // 今日时长
                                // 获取车辆今日最开始的一条设备信息
                                String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);
                                if (workHoursJson == null) {
                                    mapDataMap.put(tag, "0" + unit);
                                } else {
                                    HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                                    mapDataMap.put(tag, workHoursMap.get("workHours") + unit);
                                }
                            }
                        }
                        break;
                    case Constants.THINGS_EngineBrand: {
                        // 厂家
                        String tagValue1 = Constants.EngineBrand.getPrizeNameByNum(tagValue);
                        if (tagValue1 != null) {
                            tagValue = tagValue1;
                        }
                        break;
                    }
                    case Constants.THINGS_lockStatus: {
                        // 锁车状态
                        String tagValue1 = Constants.LockStatus.getPrizeNameByNum(tagValue);
                        if (tagValue1 != null) {
                            tagValue = tagValue1;
                        }
                        break;
                    }
                    default:
                        break;
                }
                // 超出量程范围处理
                if (!"sample_time".equals(tag) && !Constants.THINGS_EngineBrand.contains(tag)
                        && !Constants.THINGS_lockStatus.contains(tag)) {
                    // 判断是否开启并且超出量程范围
                    int samplingWare = Integer.valueOf(detail.get("sampling_wave").toString());
                    if (samplingWare == 1) {
                        double rangeLow = Double.valueOf(detail.get("range_low").toString());
                        double rangeUpper = Double.valueOf(detail.get("range_upper").toString());
                        if (StringUtils.isBlank(tagValue)) {
                            tagValue = "-";
                        } else {
                            double value = Double.valueOf(tagValue);
                            if (value < rangeLow || rangeLow > rangeUpper) {
                                tagValue = "-";
                            }
                        }
                    }
                }
            }
            dataMap.putIfAbsent(tag, tagValue + unit);
            variableMap.put(tag, detail.get("name").toString());
        }
        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("variableName", variableMap);
        resultMap.put("data", dataMap);
        resultMap.put("mapData", mapDataMap);
        return resultMap;
    }

    public Map<String,Object> getWorkHour(String thingsId,Map<String,Object> resultMap){
        String tableName = this.selectTableByThingsId(thingsId);
        //查询数据
        Map<String, Object> carDataMapOperatingHour = toolCarDataMapper.carDataMapOperatingHour(thingsId, tableName + "_tb1", tableName + "_tb2");

        if (carDataMapOperatingHour != null && carDataMapOperatingHour.get("maxEngineTotalHours") != null && carDataMapOperatingHour.get("minEngineTotalHours") != null) {

            String maxEngineTotalHours = carDataMapOperatingHour.get("maxEngineTotalHours").toString();
            String minEngineTotalHours = carDataMapOperatingHour.get("minEngineTotalHours").toString();

            // 如果发动机总时长大于10万说明没有读取到发动机总工时的数据
            if (Double.parseDouble(maxEngineTotalHours) > 0 && Double.parseDouble(maxEngineTotalHours) < 100000) {

                resultMap.put(Constants.WORK_HOUR, (String.format("%.2f", Double.parseDouble(maxEngineTotalHours)-Double.parseDouble(minEngineTotalHours))) );

            }else {

                //今日时长
                String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);

                if (workHoursJson == null) {
                    resultMap.put(Constants.WORK_HOUR, "0");
                } else {
                    HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                    resultMap.put(Constants.WORK_HOUR, workHoursMap.get("workHours") );
                }

            }
        }else {

            //今日时长
            String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);

            if (workHoursJson == null) {
                resultMap.put(Constants.WORK_HOUR, "0");
            } else {
                HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                resultMap.put(Constants.WORK_HOUR, workHoursMap.get("workHours"));
            }
        }

        return  resultMap;
    }


    @Override
    public Map<String, Object> realDataNew(Map<String, Object> reqMap) throws MyException {

        Map<String, Object> resultMap = new HashMap<>();

        String thingsId = reqMap.get("thingsId").toString();

        String tableName = this.selectTableByThingsId(thingsId);

        //查询数据
        Map<String, Object> carDataMap = toolCarDataMapper.getCarData(thingsId);

        Map<String, Object> realDataMap = toolCarDataMapper.selectDataByThingsId(thingsId);

        if (carDataMap != null) {

            // 油耗数据
            if (carDataMap.containsKey(Constants.THINGS_FuelGauge)) {

                if (carDataMap.get(Constants.THINGS_FuelGauge) != null) {

                    if (Integer.valueOf(carDataMap.get(Constants.THINGS_FuelGauge).toString()) < 0) {
                        resultMap.put(Constants.THINGS_FuelGauge,"0%");
                    }else if (Integer.valueOf(carDataMap.get(Constants.THINGS_FuelGauge).toString()) > 100) {

                        resultMap.put(Constants.THINGS_FuelGauge,"100%");
                    }else {
                        resultMap.put(Constants.THINGS_FuelGauge,carDataMap.get(Constants.THINGS_FuelGauge)+"%");
                    }
                }else {

                    resultMap.put(Constants.THINGS_FuelGauge,"0%");
                }
            }else {

                resultMap.put(Constants.THINGS_FuelGauge,"0%");
            }

            // 信号强度
            if (carDataMap.containsKey(Constants.THINGS_CSQ)) {

                if (carDataMap.get(Constants.THINGS_CSQ) != null) {

                    resultMap.put(Constants.THINGS_CSQ,carDataMap.get(Constants.THINGS_CSQ));
                }else {

                    resultMap.put(Constants.THINGS_CSQ,"0");
                }
            }else {

                resultMap.put(Constants.THINGS_CSQ,"0");
            }

            // 电压值
            if (carDataMap.containsKey(Constants.THINGS_BatVol)) {

                if (carDataMap.get(Constants.THINGS_BatVol) != null) {

                    resultMap.put(Constants.THINGS_BatVol,carDataMap.get(Constants.THINGS_BatVol)+"V");
                }else {

                    resultMap.put(Constants.THINGS_BatVol,"0V");
                }
            }else {

                resultMap.put(Constants.THINGS_BatVol,"0V");
            }

            // 发动机转速
            if (carDataMap.containsKey(Constants.THINGS_RotateSpeed)) {

                if (carDataMap.get(Constants.THINGS_RotateSpeed) != null) {

                    resultMap.put(Constants.THINGS_RotateSpeed,carDataMap.get(Constants.THINGS_RotateSpeed));
                }else {

                    resultMap.put(Constants.THINGS_RotateSpeed,"0");
                }
            }else {

                resultMap.put(Constants.THINGS_RotateSpeed,"0");
            }

            // 水温
            if (carDataMap.containsKey(Constants.THINGS_WaterTemperature)) {

                if (carDataMap.get(Constants.THINGS_WaterTemperature) != null) {

                    resultMap.put(Constants.THINGS_WaterTemperature,carDataMap.get(Constants.THINGS_WaterTemperature));
                }else {

                    resultMap.put(Constants.THINGS_WaterTemperature,"0");
                }
            }else {

                resultMap.put(Constants.THINGS_WaterTemperature,"0");
            }

            // 机油压力
            if (carDataMap.containsKey(Constants.THINGS_OilPressure)) {

                if (carDataMap.get(Constants.THINGS_OilPressure) != null) {

                    resultMap.put(Constants.THINGS_OilPressure,carDataMap.get(Constants.THINGS_OilPressure));
                }else {

                    resultMap.put(Constants.THINGS_OilPressure,"0");
                }
            }else {

                resultMap.put(Constants.THINGS_OilPressure,"0");
            }
        }else {

            resultMap.put(Constants.THINGS_FuelGauge,"0%");
            resultMap.put(Constants.THINGS_CSQ,"0");
            resultMap.put(Constants.THINGS_BatVol,"0V");
            resultMap.put(Constants.THINGS_RotateSpeed,"0");
            resultMap.put(Constants.THINGS_WaterTemperature,"0");
            resultMap.put(Constants.THINGS_OilPressure,"0");
        }

        // 运行小时
        resultMap.put(Constants.THINGS_OperatingHours,"0h");
        //查询数据
        Map<String, Object> carDataMapOperatingHour = toolCarDataMapper.carDataMapOperatingHour(thingsId, tableName + "_tb1", tableName + "_tb2");

        if (carDataMapOperatingHour != null && carDataMapOperatingHour.get("maxEngineTotalHours") != null && carDataMapOperatingHour.get("minEngineTotalHours") != null) {

            String maxEngineTotalHours = carDataMapOperatingHour.get("maxEngineTotalHours").toString();
            String minEngineTotalHours = carDataMapOperatingHour.get("minEngineTotalHours").toString();

            // 如果发动机总工时大于10万，说明没有读取到发动机总工时的数据
            if (Double.parseDouble(maxEngineTotalHours) > 0 && Double.parseDouble(maxEngineTotalHours) < 100000) {

                resultMap.put(Constants.THINGS_OperatingHours, (String.format("%.2f", Double.parseDouble(maxEngineTotalHours)-Double.parseDouble(minEngineTotalHours))) + "h");

            }else {

                //今日时长
                String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);

                if (workHoursJson == null) {
                    resultMap.put(Constants.THINGS_OperatingHours, "0");
                } else {
                    HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                    resultMap.put(Constants.THINGS_OperatingHours, workHoursMap.get("workHours") + "h");
                }

            }
        }else {

            //今日时长
            String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);

            if (workHoursJson == null) {
                resultMap.put(Constants.THINGS_OperatingHours, "0h");
            } else {
                HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                resultMap.put(Constants.THINGS_OperatingHours, workHoursMap.get("workHours") + "h");
            }
        }

        resultMap.put("GPSsatellite",false);
        resultMap.put("hasFaultCode", true);

        if (realDataMap != null) {

            // 显示卫星数据页面
            if (realDataMap.get("GP_NUM") != null) {

                if (realDataMap.get("GP_NUM").toString().equals("1")) {

                    resultMap.put("GPSsatellite",true);
                }else {

                    resultMap.put("GPSsatellite",false);
                }
            }else {

                resultMap.put("GPSsatellite",false);
            }

            resultMap.put(Constants.THINGS_GPSlongitude,realDataMap.get(Constants.THINGS_GPSlongitude));
            resultMap.put(Constants.THINGS_GPSlatitude,realDataMap.get(Constants.THINGS_GPSlatitude));

            if (realDataMap.get("close_time") == null) {

                resultMap.put("close_time", "00:00");
            }else {

                LocalDateTime close_time = DateUtil.formatTimestampToTime((Timestamp) realDataMap.get("close_time"));

                resultMap.put("close_time", DateUtil.formatTime(close_time).substring(5, 16));
            }

            if (realDataMap.get("start_time") == null) {

                resultMap.put("start_time", "00:00");
            }else {

                LocalDateTime start_time = DateUtil.formatTimestampToTime((Timestamp) realDataMap.get("start_time"));

                resultMap.put("start_time", DateUtil.formatTime(start_time).substring(5, 16));
            }

        }else {

            resultMap.put("close_time", "00:00");
            resultMap.put("start_time", "00:00");
        }

        //先致为空字符串
        resultMap.put("workHour", "");
        resultMap.put("fuel", "");
        //如果是当天 获取当日工时
        resultMap = this.getWorkHour(thingsId, resultMap);
        //获取当日消耗燃油
        resultMap = this.getFuelConsumption(thingsId, resultMap, new HashMap<>());

        resultMap.put("status", realDataMap.get("status") );

        return resultMap;
    }

    @Override
    public Map<String, Object> selectMoreData(Map<String, Object> map) {
        // Map<String, Object> map1 = new HashMap<>();
        // List<String> params = vehicleDataMapper.selectParams();
        // Map<String, Object> keyEntity = new HashMap<>();
        // Map<String, Object> valueEntity = new HashMap<>();
        // for (int i=1; i<=params.size(); i++) {
        // keyEntity.put(String.valueOf(i), params.get(i-1));
        // valueEntity.put(String.valueOf(i), 0);
        // }
        // map1.put("keyEntity", keyEntity);
        // map1.put("valueEntity", valueEntity);

        String thingsId = Orgin.getString(map, "thingsId");
        String sid = toolCarDataMapper.selectSidByThingsId(thingsId);

        // 如果是子服务商，则查询出来父主机厂的sid
        String p_id =  tsssVehicleBrandParentDao.getPServerIdByServerId(sid);
        if(p_id != null) {
            sid = p_id;
        }

        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> hashMap = new LinkedHashMap<>();
        LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
        StringBuffer buffer = new StringBuffer();
        List<Map<String, Object>> maps = new ArrayList<>();

        String tempStr = "";

        //  如果 s_id 是测试模拟客户，则临时增加模拟设备的数据 - added at 2022年6月1日14:00:32
        if(sid.equals(Constants.wxtkjMoNiSId)) {
            hashMap.put("JYTSSD", "加压提升速度");
            linkedHashMap.put("JYTSSD", "100RPM");

            hashMap.put("HZSD", "回转速度");
            linkedHashMap.put("HZSD", "150CM/Min");

            hashMap.put("WGQXJD", "桅杆倾斜角度");
            linkedHashMap.put("WGQXJD", "30°");

            hashMap.put("ZJSD", "钻进深度");
            linkedHashMap.put("ZJSD", "60M");

            hashMap.put("NJYL", "泥浆压力");
            linkedHashMap.put("NJYL", "35Mpa");

            hashMap.put("NJLL", "泥浆流量");
            linkedHashMap.put("NJLL", "180L/Min");

            hashMap.put("SYL", "水压力");
            linkedHashMap.put("SYL", "40Mpa");

            hashMap.put("SLL", "水流量");
            linkedHashMap.put("SLL", "250L/Min");

            hashMap.put("QTYL", "气体压力");
            linkedHashMap.put("QTYL", "38Mpa");

            hashMap.put("QTLL", "气体流量");
            linkedHashMap.put("QTLL", "60L/Min");

            hashMap.put("BY1", "泵压1");
            linkedHashMap.put("BY1", "15L/Min");

            hashMap.put("BY2", "泵压2");
            linkedHashMap.put("BY2", "18L/Min");

            hashMap.put("BY3", "泵压3");
            linkedHashMap.put("BY3", "20L/Min");

            hashMap.put("BY4", "泵压4");
            linkedHashMap.put("BY4", "25L/Min");

            hashMap.put("BY5", "泵压5");
            linkedHashMap.put("BY5", "21L/Min");

            hashMap.put("SRQGZZT", "散热器工作状态");
            linkedHashMap.put("SRQGZZT", "正常");
        }

        //机型,服务商
        //TODO 卡特临时修改
        if (sid.equals(Constants.catSId)) {
            long selectExcavator = toolCarDataMapper.selectExcavator(thingsId);
            if (selectExcavator==0) {
                maps = toolCarDataMapper.selectBySidModelIdKtSpe(thingsId);
            } else {
                maps = toolCarDataMapper.selectBySidModelIdKt(thingsId);
            }
        }
        // 无锡钻通数据
        else if(sid.equals(Constants.wxztSId)) {
            maps = toolCarDataMapper.selectBySidModelIdwxzt(thingsId);
        } else if(sid.equals(Constants.hdznSId)) { // 合锻智能登高车服务商(后期需要与t_s_ss_column_model表关联获取)

            HashMap<String, Object> mapZTKZZ1 = new HashMap<>();
            mapZTKZZ1.put("english_text", "ZTKZZ1");
            mapZTKZZ1.put("text", "状态控制1");
            maps.add(mapZTKZZ1);

            HashMap<String, Object> mapZTKZZ2 = new HashMap<>();
            mapZTKZZ2.put("english_text", "ZTKZZ2");
            mapZTKZZ2.put("text", "状态控制2");
            maps.add(mapZTKZZ2);

            HashMap<String, Object> mapKGZT1 = new HashMap<>();
            mapKGZT1.put("english_text", "KGZT1");
            mapKGZT1.put("text", "开关状态1");
            maps.add(mapKGZT1);

            HashMap<String, Object> mapKGZT2 = new HashMap<>();
            mapKGZT2.put("english_text", "KGZT2");
            mapKGZT2.put("text", "开关状态2");
            maps.add(mapKGZT2);

            HashMap<String, Object> mapSBAJZT = new HashMap<>();
            mapSBAJZT.put("english_text", "SBAJZT");
            mapSBAJZT.put("text", "手柄按键状态");
            maps.add(mapSBAJZT);

            HashMap<String, Object> mapJCCZT = new HashMap<>();
            mapJCCZT.put("english_text", "JCCZT");
            mapJCCZT.put("text", "剪叉车状态");
            maps.add(mapJCCZT);

            HashMap<String, Object> mapJCCGZ1 = new HashMap<>();
            mapJCCGZ1.put("english_text", "JCCGZ1");
            mapJCCGZ1.put("text", "剪叉车故障1");
            maps.add(mapJCCGZ1);

            HashMap<String, Object> mapJCCGZ2 = new HashMap<>();
            mapJCCGZ2.put("english_text", "JCCGZ2");
            mapJCCGZ2.put("text", "剪叉车故障2");
            maps.add(mapJCCGZ2);

            HashMap<String, Object> mapJCCGZ3 = new HashMap<>();
            mapJCCGZ3.put("english_text", "JCCGZ3");
            mapJCCGZ3.put("text", "剪叉车故障3");
            maps.add(mapJCCGZ3);

            HashMap<String, Object> mapBatVol = new HashMap<>();
            mapBatVol.put("english_text", "BatVol");
            mapBatVol.put("text", "电压");
            maps.add(mapBatVol);

            HashMap<String, Object> mapDCDL = new HashMap<>();
            mapDCDL.put("english_text", "DCDL");
            mapDCDL.put("text", "电池电量");
            maps.add(mapDCDL);

            HashMap<String, Object> mapBDJGZSJ = new HashMap<>();
            mapBDJGZSJ.put("english_text", "BDJGZSJ");
            mapBDJGZSJ.put("text", "泵电机工作时间");
            maps.add(mapBDJGZSJ);

            HashMap<String, Object> mapCDCS = new HashMap<>();
            mapCDCS.put("english_text", "CDCS");
            mapCDCS.put("text", "充电次数");
            maps.add(mapCDCS);

            HashMap<String, Object> mapCZCS = new HashMap<>();
            mapCZCS.put("english_text", "CZCS");
            mapCZCS.put("text", "超载次数");
            maps.add(mapCZCS);

            HashMap<String, Object> mapDJSD = new HashMap<>();
            mapDJSD.put("english_text", "DJSD");
            mapDJSD.put("text", "电机速度");
            maps.add(mapDJSD);

            HashMap<String, Object> mapJCCJD = new HashMap<>();
            mapJCCJD.put("english_text", "JCCJD");
            mapJCCJD.put("text", "剪叉车角度");
            maps.add(mapJCCJD);

            HashMap<String, Object> mapJCCYL = new HashMap<>();
            mapJCCYL.put("english_text", "JCCYL");
            mapJCCYL.put("text", "剪叉车压力");
            maps.add(mapJCCYL);

            HashMap<String, Object> mapJCCYGWZ = new HashMap<>();
            mapJCCYGWZ.put("english_text", "JCCYGWZ");
            mapJCCYGWZ.put("text", "剪叉车摇杆位置");
            maps.add(mapJCCYGWZ);

            HashMap<String, Object> mapLockStatus = new HashMap<>();
            mapLockStatus.put("english_text", "lockStatus");
            mapLockStatus.put("text", "锁车状态");
            maps.add(mapLockStatus);
        } else {
            maps = toolCarDataMapper.selectBySidModelId(thingsId);
        }

        Map<String, Object> selectDataList = new HashMap<>();

        // 如果是灰熊动力的服务商(电车)
        if(sid.equals(Constants.hxdlSId)) {
            maps = toolCarDataMapper.selectTextDataForElectric();
            maps.forEach(item -> {
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                buffer.append(item.get("english_text").toString() + ", ");
            });

            //要查询的键集合
            String keyList = buffer.substring(0, buffer.length() - 2);
            //查询数据
            selectDataList = toolCarDataMapper.selectDataListForElectric(keyList, thingsId);
        } else {
            //机型
            List<Map<String, Object>> mapList = toolCarDataMapper.selectByModelId(thingsId);
            //默认
            List<Map<String, Object>> selectByDefault = toolCarDataMapper.selectByDefault();
            if (maps.size()!=0){
                maps.forEach(item->{
                    hashMap.put(item.get("english_text").toString(),item.get("text"));
                    buffer.append(item.get("english_text").toString()+",");
                });
            }

            if (mapList.size()!=0&&maps.size()==0){
                mapList.forEach(item->{
                    hashMap.put(item.get("english_text").toString(),item.get("text"));
                    buffer.append(item.get("english_text").toString()+",");
                });
            }
            if (selectByDefault.size()!=0&&mapList.size()==0&&maps.size()==0){
                selectByDefault.forEach(item->{
                    hashMap.put(item.get("english_text").toString(),item.get("text"));
                    buffer.append(item.get("english_text").toString()+",");
                });
            }

            //要查询的键集合
            String keyList = buffer.substring(0,buffer.length() - 1);
            //获取表名
            String tableName = this.selectTableByThingsId(thingsId);
            //查询数据
            selectDataList = toolCarDataMapper.selectDataList(keyList,
                    thingsId, tableName + "_tb1", tableName + "_tb2");
        }

        if (selectDataList!=null) {
            for (Map.Entry<String, Object> entry : selectDataList.entrySet()) {
                // 如果是灰熊动力的服务商(电车)
                if(sid.equals(Constants.hxdlSId)) {
                    Map<String, Object> unitMap = toolCarDataMapper.selectUnitForElectric(entry.getKey());
                    String unit="";
                    if (unitMap!=null) {
                        if (unitMap.get("unit") != null && !StringUtils.isEmpty(unitMap.get("unit").toString())) {
                            unit = unitMap.get("unit").toString();
                        }
                    }

                    linkedHashMap.put(entry.getKey(),entry.getValue() + unit);
                } else {
                    Map<String, Object> unitMap = toolCarDataMapper.selectUnit(entry.getKey());
                    String unit="";
                    if (unitMap!=null) {
                        if (unitMap.get("unit") != null && !StringUtils.isEmpty(unitMap.get("unit").toString())) {
                            unit = unitMap.get("unit").toString();
                        }
                    }

                    if (entry.getKey().equals("BTYYYWD"))
                    {
                        tempStr = entry.getValue().toString();
                    }

                    linkedHashMap.put(entry.getKey(),entry.getValue() + unit);
                }

                // 合锻智能登高车服务商在数据库的值的协议转换处理
                if(sid.equals(Constants.hdznSId)) {
                    if(entry.getKey().equals("ZTKZZ1")) {
                        String ZTKZZ1Result = Constants.getZTKZZ1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), ZTKZZ1Result.equals("") ? "/" : ZTKZZ1Result);
                    } else if(entry.getKey().equals("ZTKZZ2")) {
                        String ZTKZZ2Result = Constants.getZTKZZ2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), ZTKZZ2Result.equals("") ? "/" : ZTKZZ2Result);
                    } else if(entry.getKey().equals("KGZT1")) {
                        String KGZT1Result = Constants.getKGZT1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), KGZT1Result.equals("") ? "/" : KGZT1Result);
                    } else if(entry.getKey().equals("KGZT2")) {
                        String KGZT2Result = Constants.getKGZT2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), KGZT2Result.equals("") ? "/" : KGZT2Result);
                    } else if(entry.getKey().equals("SBAJZT")) {
                        String SBAJZTResult = Constants.getSBAJZTResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), SBAJZTResult.equals("") ? "/" : SBAJZTResult);
                    } else if(entry.getKey().equals("JCCZT")) {
                        String JCCZTResult = Constants.getJCCZTResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), JCCZTResult.equals("") ? "/" : JCCZTResult);
                    } else if(entry.getKey().equals("JCCGZ1")) {
                        String JCCGZ1Result = Constants.getJCCGZ1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), JCCGZ1Result.equals("") ? "/" : JCCGZ1Result);
                    } else if(entry.getKey().equals("JCCGZ2")) {
                        String JCCGZ2Result = Constants.getJCCGZ2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), JCCGZ2Result.equals("") ? "/" : JCCGZ2Result);
                    } else if(entry.getKey().equals("JCCGZ3")) {
                        String JCCGZ3Result = Constants.getJCCGZ3Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), JCCGZ3Result.equals("") ? "/" : JCCGZ3Result);
                    } else if(entry.getKey().equals("lockStatus")) {    // 如果是合锻智能登高车服务商，锁车状态需要由10进制转为二进制，从二进制里面获取0或1
                        String lockStatusResult = Constants.getLockStatusResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.getValue().toString()))));
                        linkedHashMap.put(entry.getKey(), lockStatusResult.equals("") ? "/" : lockStatusResult);
                    }
                }
            }
        } else {
            for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
                linkedHashMap.put(entry.getKey(),'0');
            }
        }

        // 如果是灰熊动力的服务商(电车)，需要加上 电池各温度信息 和  电池电芯电压 信息(一对多)
        if(sid.equals(Constants.hxdlSId)) {
            List<Map<String, Object>> dataForElectricB2V = toolCarDataMapper.selectDataForElectricB2V(thingsId);

            for (Map<String, Object> dataMap: dataForElectricB2V) {
                dataMap.forEach((k, v) -> {
                    if(v != null) {
                        String randomStr = UuidUtil.get32UUID();

                        String valueStr = v.toString();
                        hashMap.put(k + randomStr, valueStr.substring(0, valueStr.indexOf("：")));
                        linkedHashMap.put(k + randomStr, valueStr.substring(valueStr.indexOf("：") + 1, valueStr.length() - 1));
                    }
                });
            }
        }

        // 如果有胎压数据的，返回胎压的数据
        List<Map<String, Object>> tireList = toolCarDataMapper.selectTirePressureData(thingsId);
        tireList.forEach(item -> {
            String axis = item.get("axis").toString();
            String tyre = item.get("tyre").toString();
            String tire_pressure = item.get("tire_pressure").toString();
            String temperature = item.get("temperature").toString();

            Map<String,Object> keyMap = new HashMap<>();

            keyMap.put("axis"+axis+"tyre"+tyre,"第"+axis+"轴"+tyre+"胎");

            hashMap.putAll(keyMap);

            Map<String,Object> valueMap = new HashMap<>();

            valueMap.put("axis"+axis+"tyre"+tyre,tire_pressure+"Bar"+" "+temperature+"℃");

            linkedHashMap.putAll(valueMap);
        });

        // 泰州切削液浓度，临时判断
        if (thingsId.equals("19230310023"))
        {
            if (linkedHashMap.containsKey("BTYYYWD"))
            {
                Map<String,Object> keyMap = new HashMap<>();

                keyMap.put("qxynddy","切削液浓度(电压)");

                hashMap.putAll(keyMap);

                Map<String,Object> valueMap = new HashMap<>();

                Double yyywdIO = Double.parseDouble(tempStr.toString());

                Double btyyywd = ((yyywdIO + 11 + 55)/8.75/1000)*980;

                valueMap.put("qxynddy", String.format("%.1f",btyyywd) + "V");

                linkedHashMap.putAll(valueMap);
            }

        }

        map1.put("keyEntity",hashMap);
        map1.put("valueEntity",linkedHashMap);
        return map1;
    }

    public static String DecimalToBinary(int decimalData) {
        String result = "";
        // 将decimalData放入到for循环里面，每次循环结束都除以2
        for(int i = decimalData; i > 0; i /= 2) {
            // 将i的数值对2取余，然后进行字符串的拼接，最后赋值给result
            result = i % 2 + result;
        }

        // 不满 8 位，用 0 补足 8 位
        String zoreStr = "";
        if(result.length() < 8) {
            for(int j = 0; j < 8 - result.length(); j++) {
                zoreStr += "0";
            }
        }

        return zoreStr + result;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexString
     * @return
     */
    public static String hexString2binaryString(String hexString) {
        // 16进制转10进制
        BigInteger sint = new BigInteger(hexString, 16);
        // 10进制转2进制
        String result = sint.toString(2);

        // 不满 8 位，用 0 补足 8 位
        String zoreStr = "";
        if(result.length() < 8) {
            for(int j = 0; j < 8 - result.length(); j++) {
                zoreStr += "0";
            }
        }

        return zoreStr + new StringBuilder(result);
    }

    /**
     * 字符串翻转，譬如 1000100 翻转为 0010001
     * @param binaryData
     * @return
     */
    public static String InvertBinary(String binaryData) {
        String strTemp = "";
        String[] strArr = binaryData.split("");
        for (int i = strArr.length - 1; i >= 0; i--) {
            strTemp += strArr[i];
        }

        return strTemp;
    }

    //通过thingsid获取表名
    public  String selectTableByThingsId(String thingsId){
        Map<String, Object> map1 = toolCarDataMapper.selectByThingsId(thingsId);

        String tableName = "pc_car_";
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(new Date());
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String bsd = "";
        tableName = tableName + "other_" + year + "_W" + weekOfYear;

        if (map1 != null) {

            if (map1.containsKey("s_id")) {

                if (map1.get("s_id") != null) {

                    bsd = map1.get("bsd").toString();

                    tableName = "pc_car_";
                    tableName = tableName + bsd.substring(bsd.length() - 6, bsd.length())
                            + "_" + year + "_W" + weekOfYear;
                }
            }
        }

        return tableName;
    }

    //通过thingsid获上周表名
    public  String selectTableByThingsIdLast(String thingsId){
        Map<String, Object> map1 = toolCarDataMapper.selectByThingsId(thingsId);

        String tableName = "pc_car_";
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(new Date());
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String bsd = "";
        tableName = tableName + "other_" + year + "_W" + (weekOfYear-1);

        if (map1 != null) {

            if (map1.containsKey("s_id")) {
                if (map1.get("s_id") != null) {

                    bsd = map1.get("bsd").toString();

                    tableName = "pc_car_";
                    tableName = tableName + bsd.substring(bsd.length() - 6, bsd.length())
                            + "_" + year + "_W" + (weekOfYear-1);
                }
            }
        }

        return tableName;
    }

    //通过thingsid获取表名
    public  String selectTableByThingsIdByDate(String thingsId,Date date){
        Map<String, Object> map1 = toolCarDataMapper.selectByThingsId(thingsId);

        String tableName = "pc_car_";
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String bsd = "";
        tableName = tableName + "other_" + year + "_W" + weekOfYear;

        if (map1 != null) {

            if (map1.containsKey("s_id")) {

                if (map1.get("s_id") != null) {

                    bsd = map1.get("bsd").toString();

                    tableName = "pc_car_";
                    tableName = tableName + bsd.substring(bsd.length() - 6, bsd.length())
                            + "_" + year + "_W" + weekOfYear;
                }
            }
        }

        return tableName;
    }


    //通过thingsid获上周表名
    public  String selectTableByThingsIdLastByDate(String thingsId,Date date){
        Map<String, Object> map1 = toolCarDataMapper.selectByThingsId(thingsId);

        String tableName = "pc_car_";
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String bsd = "";
        tableName = tableName + "other_" + year + "_W" + (weekOfYear-1);

        if (map1 != null) {

            if (map1.containsKey("s_id")) {

                if (map1.get("s_id") != null) {

                    bsd = map1.get("bsd").toString();

                    tableName = "pc_car_";
                    tableName = tableName + bsd.substring(bsd.length() - 6, bsd.length())
                            + "_" + year + "_W" + (weekOfYear-1);
                }
            }
        }

        return tableName;
    }

    @Override
    public ResponseBean selectHistoryData(Map<String, Object> map) {
        Date startTime = Orgin.getDateTime(map, "startTime");
        Date endTime = Orgin.getDateTime(map, "endTime");
        String thingsId = Orgin.getString(map, "thingsId");
        int mapmatch = Orgin.getIntValue(map, "mapmatch");
        String[] activeProfiles = env.getActiveProfiles();
        String activeProfile = activeProfiles[0];
        if (activeProfile.equals("prod")){
            activeProfile="DIS";
        }else if (activeProfile.equals("dev")){
            activeProfile="DEV";
        }
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        //添加实时点
        Map<String, Object> selectCarDate = toolCarDataMapper.selectCarDate(thingsId);
        stringObjectHashMap.put("realDate",
                Orgin.getDoubleValue(selectCarDate,"GPSlongitude")+","+
                        Orgin.getDoubleValue(selectCarDate,"GPSlatitude"));
        Map<String, Object> map1 = toolCarDataMapper.selectTrid(activeProfile+thingsId);
        if (map1!=null){
            Integer trid = Integer.valueOf(map1.get("trid").toString());
            Integer tid = Integer.valueOf(map1.get("tid").toString());

            // 18、19的设备都开纠偏
            if (Constants.is18Or19(thingsId)) {
                mapmatch = 1;
            }

            // 判断是否是192808编码(该编码开头的为无线定位设备)开头的thingsid
            if(Constants.is192808(thingsId)) {
                mapmatch = 0;
            }

            Map<String, Object> pointList = AddressGEOUtil.pointList(trid, tid, startTime.getTime(), endTime.getTime(),1,mapmatch);
            Integer parseObject = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
            if (parseObject==10000){
                if(pointList.get("data") != null) {
                    Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
                    List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
                    double distance = Double.parseDouble(parseObject2.get(0).get("distance") + "") / 1000;
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);
                    nf.setRoundingMode(RoundingMode.UP);
                    stringObjectHashMap.put("distance", nf.format(distance));
                    JSONArray array = JSON.parseArray(parseObject2.get(0).get("points").toString());
                    if (array.size() == 999) {
                        JSONArray jsonArray = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 2, mapmatch);
                        array.addAll(jsonArray);
                        if (jsonArray.size() == 999) {
                            JSONArray jsonArray1 = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 3, mapmatch);
                            array.addAll(jsonArray1);
                            if (jsonArray.size() == 999) {
                                JSONArray jsonArray2 = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 4, mapmatch);
                                array.addAll(jsonArray2);
                            }
                        }
                    }


                    // 如果是18010的铝壳版设备不需要过滤算法
                    if (Constants.is18Or19(thingsId)) {
                        stringObjectHashMap.put("points", array);
                        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", stringObjectHashMap);
                    }

                    ArrayList<Map<String, Object>> locationList = new ArrayList<>();

                    array.forEach(item -> {

                        JSONObject jsonObject = (JSONObject) item;

                        String[] location = jsonObject.get("location").toString().split(",");

                        String longitude = location[0].toString();
                        String latitude = location[1].toString();

                        Map<String, Object> gpsMap = new HashMap<>();

                        gpsMap.put("GPSlongitude", longitude);
                        gpsMap.put("GPSlatitude", latitude);

                        locationList.add(gpsMap);
                    });

                    ArrayList<Map<String, Object>> finalLocationList = locationList;

                    if (finalLocationList.size() > 1) {
                        // 根据约定过滤错误数据,相邻数据相等的都不要
                        finalLocationList = CarDataStatisticsUtil.locationFilter(finalLocationList);
                        // 对数据进行标准差值比较过滤
                        finalLocationList = CarDataStatisticsUtil.locationStandardDeviationFilter(finalLocationList);
                    }

                    ArrayList<Map<String, Object>> tempArray = new ArrayList();

                    finalLocationList.forEach(item -> {

                        Map<String, Object> tempMap = new HashMap<>();

                        tempMap.put("location", item.get(Constants.THINGS_GPSlongitude) + "," + item.get(Constants.THINGS_GPSlatitude));

                        tempArray.add(tempMap);
                    });
                    stringObjectHashMap.put("points", tempArray);
                }
            }
        }
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", stringObjectHashMap);
    }


    @Override
    public ResponseBean selectHistoryDataByStartDateAndEndDate(Map<String, Object> map) {
        Date startTimeParm = Orgin.getDateTime(map, "startTime");
        Date endTimeParm= Orgin.getDateTime(map, "endTime");
        String thingsId = Orgin.getString(map, "thingsId");
        int mapmatch = Orgin.getIntValue(map, "mapmatch");
        String[] activeProfiles = env.getActiveProfiles();
        String activeProfile = activeProfiles[0];
        if (activeProfile.equals("prod")){
            activeProfile="DIS";
        }else if (activeProfile.equals("dev")){
            activeProfile="DEV";
        }
        activeProfile="DIS";
        List<Map<String, Object>> liststringObjectHashMap=new ArrayList<>();

        Map<String, Object> stringObjectHashMap = null;
        List<Date> dateList=DateUtils.getDateDays(startTimeParm,endTimeParm);
        int dateListSize = dateList.size();

        for (int i = 0; i < dateListSize; i++) {
            Date dateOne = dateList.get(i);
            stringObjectHashMap = new HashMap<>();
            //添加实时点
            Map<String, Object> selectCarDate = toolCarDataMapper.selectCarDate(thingsId);
            stringObjectHashMap.put("realDate", Orgin.getDoubleValue(selectCarDate,"GPSlongitude")+","+ Orgin.getDoubleValue(selectCarDate,"GPSlatitude"));
            Map<String, Object> map1 = toolCarDataMapper.selectTrid(activeProfile+thingsId);
            if (map1!=null){
                Integer trid = Integer.valueOf(map1.get("trid").toString());
                Integer tid = Integer.valueOf(map1.get("tid").toString());

                // 18、19的设备都开纠偏
                if (Constants.is18Or19(thingsId)) {
                    mapmatch = 1;
                }
                // 判断是否是192808编码(该编码开头的为无线定位设备)开头的thingsid
                if(Constants.is192808(thingsId)) {
                    mapmatch = 0;
                }
                Long startTimeNew=0L;
                Long endTimeNew=0L;
                if (i == 0) {
                    startTimeNew =  dateOne.getTime();
                    endTimeNew   =  DateUtils.getEndOfDayNew(dateOne).getTime();
                } else if (i > 0 && i <dateListSize-1 ) {
                    startTimeNew =  DateUtils.getStartOfDayNew(dateOne).getTime();
                    endTimeNew   =  DateUtils.getEndOfDayNew(dateOne).getTime();
                } else if (i == dateListSize - 1) {
                    startTimeNew =  DateUtils.getStartOfDayNew(dateOne).getTime();
                    endTimeNew   =  endTimeParm.getTime();
                }



                Map<String, Object> pointList = AddressGEOUtil.pointList(trid, tid,startTimeNew ,endTimeNew,1,mapmatch);
                Integer parseObject = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
                if (parseObject==10000){
                    if(pointList.get("data") != null) {
                        Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
                        List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
                        double distance = Double.parseDouble(parseObject2.get(0).get("distance") + "") / 1000;
                        NumberFormat nf = NumberFormat.getNumberInstance();
                        nf.setMaximumFractionDigits(2);
                        nf.setRoundingMode(RoundingMode.UP);
                        stringObjectHashMap.put("distance", nf.format(distance));
                        JSONArray array = JSON.parseArray(parseObject2.get(0).get("points").toString());
                        if (array.size() == 999) {
                            JSONArray jsonArray = this.getPoints(trid, tid, startTimeNew,endTimeNew, 2, mapmatch);
                            array.addAll(jsonArray);
                            if (jsonArray.size() == 999) {
                                JSONArray jsonArray1 = this.getPoints(trid, tid, startTimeNew, endTimeNew, 3, mapmatch);
                                array.addAll(jsonArray1);
                                if (jsonArray.size() == 999) {
                                    JSONArray jsonArray2 = this.getPoints(trid, tid, startTimeNew,endTimeNew, 4, mapmatch);
                                    array.addAll(jsonArray2);
                                }
                            }
                        }
                        // 如果是18010的铝壳版设备不需要过滤算法
                        if (Constants.is18Or19(thingsId)) {
                            stringObjectHashMap.put("points", array);
                            liststringObjectHashMap.add(stringObjectHashMap);
                        }else{
                            ArrayList<Map<String, Object>> locationList = new ArrayList<>();
                            array.forEach(item -> {
                                JSONObject jsonObject = (JSONObject) item;
                                String[] location = jsonObject.get("location").toString().split(",");
                                String longitude = location[0].toString();
                                String latitude = location[1].toString();
                                Map<String, Object> gpsMap = new HashMap<>();
                                gpsMap.put("GPSlongitude", longitude);
                                gpsMap.put("GPSlatitude", latitude);
                                locationList.add(gpsMap);
                            });

                            ArrayList<Map<String, Object>> finalLocationList = locationList;
                            if (finalLocationList.size() > 1) {
                                // 根据约定过滤错误数据,相邻数据相等的都不要
                                finalLocationList = CarDataStatisticsUtil.locationFilter(finalLocationList);
                                // 对数据进行标准差值比较过滤
                                finalLocationList = CarDataStatisticsUtil.locationStandardDeviationFilter(finalLocationList);
                            }
                            ArrayList<Map<String, Object>> tempArray = new ArrayList();
                            finalLocationList.forEach(item -> {
                                Map<String, Object> tempMap = new HashMap<>();
                                tempMap.put("location", item.get(Constants.THINGS_GPSlongitude) + "," + item.get(Constants.THINGS_GPSlatitude));
                                tempArray.add(tempMap);
                            });
                            stringObjectHashMap.put("points", tempArray);
                        }
                    }
                }
            }
        }
        Map<String, Object> stringObjectHashMapLastData = new HashMap<>();
        if(CollUtil.isNotEmpty(liststringObjectHashMap)){
            if(liststringObjectHashMap.size()==1){
                stringObjectHashMapLastData=liststringObjectHashMap.get(0);
            }else{
                Map<String, Object> mapByRealDate=stringObjectHashMap=liststringObjectHashMap.get(0);
                stringObjectHashMapLastData.put("realDate",mapByRealDate.get("realDate"));
                ArrayList<Map<String, Object>> tempArrayNew = new ArrayList();
                double distanceDate=0.0;
                for (Map<String, Object> mapData:liststringObjectHashMap) {
                    distanceDate=distanceDate+Double.parseDouble((String) mapData.get("distance"));
                    JSONArray array=(JSONArray) mapData.get("points");
                    ArrayList<Map<String, Object>> tempArrayNewLast =(ArrayList<Map<String, Object>>)stringObjectHashMapLastData.get("points");
                    if(CollUtil.isNotEmpty(tempArrayNewLast)){
                        Map<String, Object> mapDataNew=new HashMap<>();
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject nodeData = (JSONObject) array.get(i);
                            mapDataNew.put("location",nodeData.getString("location"));
                            tempArrayNewLast.add(mapDataNew);
                        }
                        stringObjectHashMapLastData.put("points",tempArrayNewLast);
                    }else{
                        ArrayList<Map<String, Object>> tempArray = new ArrayList();
                        Map<String, Object> mapDataNew=new HashMap<>();
                        for (int i = 0; i < array.size(); i++) {
                            mapDataNew=new HashMap<>();
                            JSONObject nodeData = (JSONObject) array.get(i);
                            mapDataNew.put("location",nodeData.getString("location"));
                            tempArray.add(mapDataNew);
                        }

                        stringObjectHashMapLastData.put("points",tempArray);
                    }
                }
                NumberFormat nf = NumberFormat.getNumberInstance();
                nf.setMaximumFractionDigits(2);
                nf.setRoundingMode(RoundingMode.UP);
                stringObjectHashMapLastData.put("distance", nf.format(distanceDate));

            }
        }
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", stringObjectHashMapLastData);
    }


    @Override
    public ResponseBean selectHistoryDataNew(Map<String, Object> map) {
        Date startTime = Orgin.getDateTime(map, "startTime");
        Date endTime = Orgin.getDateTime(map, "endTime");
        String thingsId = Orgin.getString(map, "thingsId");
        int mapmatch = Orgin.getIntValue(map, "mapmatch");
        String[] activeProfiles = env.getActiveProfiles();
        String activeProfile = activeProfiles[0];
        if (activeProfile.equals("prod")) {
            activeProfile = "DIS";
        } else if (activeProfile.equals("dev")) {
            activeProfile = "DEV";
        }
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        // 添加实时点
        Map<String, Object> selectCarDate = toolCarDataMapper.selectCarDate(thingsId);
        stringObjectHashMap.put("realDate",
                Orgin.getDoubleValue(selectCarDate,"GPSlongitude")+","+
                        Orgin.getDoubleValue(selectCarDate,"GPSlatitude"));
        Map<String, Object> map1 = toolCarDataMapper.selectTrid(activeProfile+thingsId);
        if (map1 != null) {
            Integer trid = Integer.valueOf(map1.get("trid").toString());
            Integer tid = Integer.valueOf(map1.get("tid").toString());

            mapmatch = 0; // 第一步、先设置不纠偏(mapmatch=0)

            Map<String, Object> pointList = AddressGEOUtil.pointList(trid, tid, startTime.getTime(), endTime.getTime(),1, mapmatch);
            Integer parseObject = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
            if (parseObject == 10000) {
                if(pointList.get("data") != null) {
                    Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
                    List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
                    double distance = Double.parseDouble(parseObject2.get(0).get("distance") + "") / 1000;
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);
                    nf.setRoundingMode(RoundingMode.UP);
                    stringObjectHashMap.put("distance", nf.format(distance));
                    JSONArray array = JSON.parseArray(parseObject2.get(0).get("points").toString());
                    if (array.size() == 999) {
                        JSONArray jsonArray = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 2, mapmatch);
                        array.addAll(jsonArray);
                        if (jsonArray.size() == 999) {
                            JSONArray jsonArray1 = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 3, mapmatch);
                            array.addAll(jsonArray1);
                            if (jsonArray.size() == 999) {
                                JSONArray jsonArray2 = this.getPoints(trid, tid, startTime.getTime(), endTime.getTime(), 4, mapmatch);
                                array.addAll(jsonArray2);
                            }
                        }
                    }

                    List intervalPointsList = new ArrayList();
                    HashMap<String, Object> intervalMap = new HashMap<>();
                    for(int i = 0; i < array.size(); i++) {
                        Map<String, Object> pointMap = (Map<String, Object>)array.get(i); // 当前循环的具体坐标点的信息
                        long locatetime = Long.parseLong(pointMap.get("locatetime").toString());
                        int status = Integer.parseInt(((Map<String, Object>)pointMap.get("props")).get("status").toString());

                        Map<String, Object> pointMapLast = new HashMap<>();
                        long locatetimeLast = 0L;
                        int statusLast = 0;
                        if(i != 0) {
                            pointMapLast = (Map<String, Object>)array.get(i - 1); // 循环中上一个的具体坐标点的信息
                            locatetimeLast = Long.parseLong(pointMapLast.get("locatetime").toString());
                            statusLast = Integer.parseInt(((Map<String, Object>)pointMapLast.get("props")).get("status").toString());
                        }

                        if(i == 0) {
                            intervalMap.put("startLocatetime", locatetime); // 第一个坐标点的创建起始时间
                        } else if(i != array.size() - 1) { // 第一个坐标点和最后一个坐标点之间的点
                            if(status != statusLast) {  // 如果 status 不相等，则添加到list，同时增加下一间隔的点的创建起始时间
                                intervalMap.put("endLocatetime", locatetimeLast);
                                intervalMap.put("status", statusLast);
                                intervalPointsList.add(intervalMap.clone());

                                intervalMap.put("startLocatetime", locatetime);
                            }
                        } else if(i == array.size() - 1) { // 如果是最后一个坐标点
                            if(status != statusLast) { // 如果 status 不相等，则添加到list，同时增加当前点的信息到下一间隔
                                intervalMap.put("endLocatetime", locatetimeLast);
                                intervalMap.put("status", statusLast);
                                intervalPointsList.add(intervalMap.clone());

                                intervalMap.put("startLocatetime", locatetime);
                                intervalMap.put("endLocatetime", locatetime);
                                intervalMap.put("status", status);
                                intervalPointsList.add(intervalMap.clone());
                            } else if (status == statusLast) {
                                intervalMap.put("endLocatetime", locatetime);
                                intervalMap.put("status", status);
                                intervalPointsList.add(intervalMap.clone());
                            }
                        }
                    }
                    System.out.println(intervalPointsList);

                    // 第二步 设置纠偏(mapmatch=1)
                    List resultList = new ArrayList();
                    HashMap<String, Object> newPointsArrMap = new HashMap<>();
                    intervalPointsList.forEach(item -> {
                        Map<String, Object> itemMap = (Map<String, Object>)item;
                        Long startTimeForMapMath = Long.parseLong(itemMap.get("startLocatetime").toString());
                        Long endTimeForMapMath = Long.parseLong(itemMap.get("endLocatetime").toString());

                        System.out.println(startTimeForMapMath);
                        System.out.println(endTimeForMapMath);
                        System.out.println(itemMap.get("status"));

                        Map<String, Object> pointListForMapMath = AddressGEOUtil.pointList(trid, tid, startTimeForMapMath, endTimeForMapMath, 1, 1);
                        Integer parseObjectForMapMath = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
                        if (parseObjectForMapMath == 10000) {
                            if (pointListForMapMath.get("data") != null) {
                                Map parseObjectForMapMath1 = JSON.parseObject(pointListForMapMath.get("data").toString(), Map.class);
                                List<Map<String, Object>> parseObjectForMapMath2 = JSON.parseObject(parseObjectForMapMath1.get("tracks").toString(), List.class);
                                double distanceForMapMath = Double.parseDouble(parseObjectForMapMath2.get(0).get("distance") + "") / 1000;
                                NumberFormat nfForMapMath = NumberFormat.getNumberInstance();
                                nfForMapMath.setMaximumFractionDigits(2);
                                nfForMapMath.setRoundingMode(RoundingMode.UP);

                                JSONArray arrayForMapMath = JSON.parseArray(parseObjectForMapMath2.get(0).get("points").toString());
                                if (arrayForMapMath.size() == 999) {
                                    JSONArray jsonArrayForMapMath = this.getPoints(trid, tid, startTimeForMapMath, endTimeForMapMath, 2, 1);
                                    arrayForMapMath.addAll(jsonArrayForMapMath);
                                    if (jsonArrayForMapMath.size() == 999) {
                                        JSONArray jsonArrayForMapMath1 = this.getPoints(trid, tid, startTimeForMapMath, endTimeForMapMath, 3, 1);
                                        arrayForMapMath.addAll(jsonArrayForMapMath1);
                                        if (jsonArrayForMapMath1.size() == 999) {
                                            JSONArray jsonArrayForMapMath2 = this.getPoints(trid, tid, startTimeForMapMath, endTimeForMapMath, 4, 1);
                                            arrayForMapMath.addAll(jsonArrayForMapMath2);
                                        }
                                    }
                                }

                                ArrayList locationList = new ArrayList<>();
                                arrayForMapMath.forEach(it -> {
                                    JSONObject jsonObject = (JSONObject) it;
                                    String[] location = jsonObject.get("location").toString().split(",");
                                    String longitude = location[0].toString();
                                    String latitude = location[1].toString();
                                    locationList.add(longitude + "," + latitude);
                                });
//
//                                ArrayList<Map<String, Object>> finalLocationList = locationList;
//                                if (finalLocationList.size() > 1) {
//                                    // 根据约定过滤错误数据,相邻数据相等的都不要
//                                    finalLocationList = CarDataStatisticsUtil.locationFilter(finalLocationList);
//                                    // 对数据进行标准差值比较过滤
//                                    finalLocationList = CarDataStatisticsUtil.locationStandardDeviationFilter(finalLocationList);
//                                }
//
//                                ArrayList tempArray = new ArrayList();
//                                locationList.forEach(ite -> {
//                                    // Map<String, Object> tempMap = new HashMap<>();
//                                    // tempMap.put("location", ite.get(Constants.THINGS_GPSlongitude) + "," + ite.get(Constants.THINGS_GPSlatitude));
//                                    tempArray.add(ite.get(Constants.THINGS_GPSlongitude) + "," + ite.get(Constants.THINGS_GPSlatitude));
//                                });

//                                System.out.println(tempArray);
                                System.out.println(arrayForMapMath);

                                newPointsArrMap.put("status", itemMap.get("status"));
                                newPointsArrMap.put("points", locationList.clone());
                                resultList.add(newPointsArrMap.clone());
                            }
                        }
                    });
                    stringObjectHashMap.put("points", resultList);
                }
            }
        }

        stringObjectHashMap.put("hasStatus", 1);
        System.out.println(stringObjectHashMap);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", stringObjectHashMap);
    }

    public JSONArray  getPoints(Integer trid, Integer tid, Long starttime, Long endtime,Integer page,int mapmatch){
        Map<String, Object> pointList = AddressGEOUtil.pointList(trid, tid, starttime, endtime,page,mapmatch);
        Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
        List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
        JSONArray array = JSON.parseArray(parseObject2.get(0).get("points").toString());
        return  array;
    }


    private void setAdviceState(Map<String, Object> mapDataMap, Map<String, Object> carDataMap, String tableName, String thingsId) {
        if (carDataMap == null) {
            mapDataMap.put("adviceState", "暂无状态");
            mapDataMap.put("adviceTime", "无");
            mapDataMap.put("hasFaultCode", false);
        } else {
            boolean hasFaultCode = false;
            if (carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + "1") != null) {
                hasFaultCode = true;
            }
            mapDataMap.put("hasFaultCode", hasFaultCode);
            LocalDateTime closeTime = DateUtil.formatTimestampToTime((Timestamp) carDataMap.get("sample_time"));
            Duration duration = Duration.between(closeTime, LocalDateTime.now());

            if (carDataMap.containsKey(Constants.THINGS_IsCAT)) {

                if (carDataMap.containsKey("OperatingHours")) {

                    Double operatingHours = Double.parseDouble(carDataMap.get("OperatingHours").toString());

                    if (operatingHours > 0) {

                        this.wrapSetAdviceState(duration, carDataMap, mapDataMap, closeTime, hasFaultCode, tableName, thingsId);
                    }else {

                        mapDataMap.put("adviceState", "已关机");

                        Map<String,Object> sampleTimeMap = toolCarDataMapper.lastCarDataCANOK(tableName,thingsId);

                        if (sampleTimeMap != null) {

                            LocalDateTime sampleTime = DateUtil.formatTimestampToTime((Timestamp) sampleTimeMap.get("sample_time"));

                            mapDataMap.put("adviceTime", DateUtil.formatTime(sampleTime).substring(5, 16));
                        }else {

                            mapDataMap.put("adviceTime", "00:00");
                        }
                    }
                }

            } else if (carDataMap.containsKey(Constants.THINGS_Ignition)) {
                double ignition = Double.valueOf(carDataMap.get(Constants.THINGS_Ignition).toString());
                if (ignition >= 10) {
                    this.wrapSetAdviceState(duration, carDataMap, mapDataMap, closeTime, hasFaultCode, tableName, thingsId);
                } else {
                    mapDataMap.put("adviceState", "已关机");
                    mapDataMap.put("adviceTime", DateUtil.formatTime(closeTime).substring(5, 16));
                }
            } else {
                this.wrapSetAdviceState(duration, carDataMap, mapDataMap, closeTime, hasFaultCode, tableName, thingsId);
            }
        }
    }

    private void wrapSetAdviceState(Duration duration, Map<String, Object> carDataMap, Map<String, Object> mapDataMap, LocalDateTime closeTime, boolean hasFaultCode, String tableName, String thingsId){

        if (duration.toMinutes() > 5) {
            mapDataMap.put("adviceState", "已关机");
            mapDataMap.put("adviceTime", DateUtil.formatTime(closeTime).substring(5, 16));
        } else {
            // 获取车辆今日最开始的一条设备信息
            Map<String, Object> firstCarDataMap;

            if (carDataMap.containsKey(Constants.THINGS_Ignition)) {
                firstCarDataMap = toolCarDataMapper.firstCarDataIgnition(tableName, thingsId, true);
                if (firstCarDataMap == null) {
                    firstCarDataMap = toolCarDataMapper.firstCarDataToday(tableName, thingsId);
                }
            } else {
                firstCarDataMap = toolCarDataMapper.firstCarDataToday(tableName, thingsId);
            }
            LocalDateTime openTime;
            if (firstCarDataMap != null) {
                openTime = DateUtil.formatTimestampToTime((Timestamp) firstCarDataMap.get("sample_time"));
            } else {
                openTime = closeTime;
            }
            mapDataMap.put("adviceState", "工作中");
            mapDataMap.put("adviceTime", DateUtil.formatTime(openTime).substring(5, 16));
            this.wrapSetAdviceStateFault(hasFaultCode, carDataMap, mapDataMap);
        }
    }

    private void wrapSetAdviceStateFault(boolean hasFaultCode, Map<String, Object> carDataMap, Map<String, Object> mapDataMap){

        if ((Integer)carDataMap.get("faultCount") > 0) {

            mapDataMap.put("adviceState", "故障中");
        }
//        if (hasFaultCode && (!CarDataStatisticsUtil.equalsZero(carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + "1"))
//                || !CarDataStatisticsUtil.equalsZero(carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + "2"))
//                || !CarDataStatisticsUtil.equalsZero(carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + "3")))) {
//            if (carDataMap.get("LS1") != null) {
//                String hi1 = carDataMap.get("LS1").toString(),
//                        hi2 = carDataMap.get("LS2").toString(),
//                        hi3 = carDataMap.get("LS3").toString();
//                String realFault = Constants.HiCodeEnum.HI_CODE_1.getCode();
//                if (realFault.equals(hi1) || realFault.equals(hi2) || realFault.equals(hi3)) {
//                    mapDataMap.put("adviceState", "故障中");
//                }
//            }
//        }
    }

    @Override
    public List<Map<String, Object>> maintenanceRecords(User currentUser, Map<String, Object> reqMap) throws MyException {
        this.appPage(reqMap);
        List<Map<String, Object>> maps = toolCarDataMapper.listOrderByCarId(reqMap);
        return toolViewBoardService.listByFault(maps,currentUser.getS_id());
    }

    /**
     * 获取车辆历史轨迹
     *
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public List<Map<String, Object>> historyTrajectory(User currentUser, Map<String, Object> reqMap) throws MyException {
        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
        }
        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
        if (pcCarMap == null || pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
        }

        String intelligentId = pcCarMap.get("device_template").toString();
        String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
        reqMap.put("tableName", tableName);

        List<Map<String, Object>> carHistoryDataList = new ArrayList<>();
        // 获取无偏差经纬度
        String thingsId = reqMap.get("thingsId").toString();
        String date = reqMap.get("date").toString();

        Map<String, Object> realDataMap = new HashMap<>();
        realDataMap.put("thingsId",thingsId);
        realDataMap.put("date",DateUtil.parseDate(reqMap.get("date").toString()));
        realDataMap.put("realData",false);

        Map<String, Object> locationMap = toolCarDataMapper.getCarRealData(realDataMap);
        if (locationMap != null) {
            if (locationMap.get("history_location") != null) {
                String historyLocation = locationMap.get("history_location").toString();

                carHistoryDataList = JSON.parseObject(historyLocation, new TypeReference<List<Map<String, Object>>>() {
                });
            } else {

                Map<String, Object> data = this.getDataStatisticsObj(thingsId, intelligentId, date);
                carHistoryDataList = JSON.parseObject(data.get("history_location").toString(), new TypeReference<List<Map<String, Object>>>() {
                });
                // 保存数据
                cachedThreadPool.execute(() -> {
                    Map<String, Object> params = this.generateDataStatisticsParams(thingsId, date, null, null,
                            (Double) data.get(Constants.THINGS_GPSlongitude),
                            (Double) data.get(Constants.THINGS_GPSlatitude),
                            data.get("history_location").toString());
                    toolCarDataMapper.updateDataStatistics(params);
                });
            }
        } else {
            if (DateUtil.parseDate(date).isBefore(LocalDate.now())) {
                Map<String, Object> data = this.getDataStatisticsObj(thingsId, intelligentId, date);
                carHistoryDataList = JSON.parseObject(data.get("history_location").toString(), new TypeReference<List<Map<String, Object>>>() {
                });
                // 插入数据
                cachedThreadPool.execute(() -> {
                    Map<String, Object> params = this.generateDataStatisticsParams(thingsId, date, null, null,
                            (Double) data.get(Constants.THINGS_GPSlongitude),
                            (Double) data.get(Constants.THINGS_GPSlatitude),
                            data.get("history_location").toString());
                    toolCarDataMapper.insertDataStatistics(params);
                });
            }
        }

        for (Map<String, Object> carData : carHistoryDataList) {
            // 根据经纬度解析出地址
            String lon = carData.get("GPSlongitude").toString();
            String lat = carData.get("GPSlatitude").toString();
            double[] gps = GPSUtil.gps84_To_Gcj02(new BigDecimal(lat).doubleValue(), new BigDecimal(lon).doubleValue());
            carData.put("GPSlongitude", gps[1]);
            carData.put("GPSlatitude", gps[0]);
        }
        return carHistoryDataList;
    }

    @Override
    public Map<String, Object> getDataStatisticsObj(String thingsId,String intelligentId, String date) {

        String tableName = this.selectTableByThingsId(thingsId);

        Map<String,Object> map = new HashMap<>();

        map.put("thingsId",thingsId);
        map.put("tb1",tableName + "_tb1");
        map.put("date",date);

        ArrayList<Map<String, Object>> locationList = toolCarDataMapper.getLocationListLimit(map);

        if (locationList.size() > 1) {
            // 根据约定过滤错误数据,相邻数据相等的都不要
            locationList = CarDataStatisticsUtil.locationFilter(locationList);
            // 对数据进行标准差值比较过滤
            locationList = CarDataStatisticsUtil.locationStandardDeviationFilter(locationList);
        }
        // 获取最新经纬度数据
        Map<String, Object> lastLocation = new HashMap<>();

        if (locationList.size() > 0) {
            lastLocation = new HashMap<>(locationList.get(locationList.size() - 1));

            Double latitude = (Double) lastLocation.get(Constants.THINGS_GPSlatitude);
            Double longitude = (Double) lastLocation.get(Constants.THINGS_GPSlongitude);

            Map<String,Object> newLocation = toolCarDataMapper.getnewLocationLimit(map);

            if (newLocation != null) {

                Double newlatitude = (Double) newLocation.get(Constants.THINGS_GPSlatitude);
                Double newlongitude = (Double) newLocation.get(Constants.THINGS_GPSlongitude);

                // 判断上下两个精度番位在1范围内
                if (Math.abs(newlatitude - latitude) < 1
                        && Math.abs(newlongitude - longitude) < 1) {

                    lastLocation.put(Constants.THINGS_GPSlatitude,newlatitude);
                    lastLocation.put(Constants.THINGS_GPSlongitude,newlongitude);
                    lastLocation.put("things_id",thingsId);
                }
            }
        }else {

            lastLocation = toolCarDataMapper.getnewLocationLimit(map);
        }

        if (lastLocation == null) {

            lastLocation = new HashMap<>();
        }

        locationList.add(lastLocation);

        String locations = JSON.toJSONString(locationList);

        lastLocation.put("thingsId", thingsId);
        lastLocation.put("history_location", locations);
        lastLocation.put("date", LocalDate.now());

        System.out.println("物联网关GPS更新返回结果：" + thingsId);

        return lastLocation;
    }

    /**
     * 实时数据参数
     * @param thingsId 设备号
     * @param date 日期
     * @param workHoursJson 工作时长json
     * @param fuelGauge 油位(%)
     * @param GPSlongitude 经度
     * @param GPSlatitude 纬度
     * @return
     */
    private Map<String, Object> generateDataStatisticsParams(String thingsId, String date, String workHoursJson,
                                                             String fuelGauge, Double GPSlongitude, Double GPSlatitude,
                                                             String historyLocation) {
        Map<String, Object> params = new HashMap<>(16);
        params.put("thingsId", thingsId);
        params.put("date", date);
        params.put("workHoursJson", workHoursJson);
        params.put("fuelGauge", fuelGauge);
        params.put("GPSlongitude", GPSlongitude);
        params.put("GPSlatitude", GPSlatitude);
        params.put("history_location", historyLocation);
        return params;
    }

    @Override
    public Map<String, Object> carWorkingHoursStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {

        LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString());
        LocalDate endTime = DateUtil.parseDate(reqMap.get("endTime").toString());
        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            return carDataMocha.getCarWorkingHoursStatistics(startTime, endTime);
        }
        // 获取列表
        List<Map<String, Object>> runningHoursList = this.getRunningHoursList(reqMap);
        // 补充数据
        runningHoursList = this.processData(runningHoursList, startTime, endTime);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", runningHoursList);
        // 设置工时数据
        CarDataStatisticsUtil.setHourData(runningHoursList, endTime, resultMap);
        return resultMap;
    }

    /**
     * 运行时长列表
     * @param reqMap
     * @return
     * @throws MyException
     */
    @Override
    public List<Map<String, Object>> getRunningHoursList(Map<String, Object> reqMap) throws MyException {
        List<Map<String, Object>> workHoursList = toolCarDataMapper.listWorkHours(reqMap);
        // 获取数据列表
        return CarDataStatisticsUtil.getConsumption(workHoursList);
    }

    /**
     * 车辆油耗统计
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String, Object> carFuelConsumptionStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {

        // 获取时间
        LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString());
        LocalDate endTime = DateUtil.parseDate(reqMap.get("endTime").toString());
        // 判断当前用户是否是游客
        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            return carDataMocha.getCarFuelConsumptionWorkHoursStatistics(startTime, endTime);
        } else {
            // 设置服务商id
            reqMap.put("sId", currentUser.getS_id());
        }
        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
        if (pcCarMap == null || pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
        }
        String intelligentTemplateId = pcCarMap.get("device_template").toString(),
                thingsId = reqMap.get("thingsId").toString(),
                tableName = ThingsData.getTableName(intelligentTemplateId);
        // 获取油箱容量
//        int tankCapacity = this.getTankCapacity(thingsId);

        // 获取每日油耗列表
        List<Map<String, Object>> fuelConsumptionList;
        // 封装数据列表
        List<Map<String, Object>> dailyFuelConsumptionList;
        // 总耗油
        double totalFuelConsumption;
        // 总工时
        double totalRunningHours;

        // 判断模版是否含有Ignition字段，如果有按照TotalFuelAmount总燃油消耗每天的差值来计算燃油消耗，负责按照燃油百分比FuelGauge来计算
//        if (toolCarDataMapper.getIntelligentTemplateDetail(Constants.THINGS_Ignition, intelligentTemplateId) != null) {
        fuelConsumptionList = toolCarDataMapper.getEveryDayFuelAmount(thingsId, tableName);
        fuelConsumptionList = this.getOilConsumption(fuelConsumptionList);
//        } else {
//            reqMap.put("tableName", tableName);
//            reqMap.put("isMax", true);
//            reqMap.put("tag", FuelGauge);
//            // 每个时间段开始时间油位
//            List<Map<String, Object>> firstHistoryDataList = toolCarDataMapper.borderHourlyData(reqMap);
//            // 每个时间段最大峰值油位
//            List<Map<String, Object>> maximumHourlyPeakList = toolCarDataMapper.hourlyPeak(reqMap);
//            reqMap.put("isMax", false);
//            reqMap.put("tag", FuelGauge);
//            // 每个时间段结束时间油位
//            List<Map<String, Object>> lastHistoryDataList = toolCarDataMapper.borderHourlyData(reqMap);
//            // 每个时间段最小峰值油位
//            List<Map<String, Object>> minimumHourlyPeakList = toolCarDataMapper.hourlyPeak(reqMap);
//            // 计算油位获取每日数据差
//            fuelConsumptionList = this.getOilConsumption(maximumHourlyPeakList, minimumHourlyPeakList, firstHistoryDataList, lastHistoryDataList, tankCapacity);
//
//        }
        dailyFuelConsumptionList = this.processData(fuelConsumptionList, startTime, endTime);
        totalFuelConsumption = dailyFuelConsumptionList.stream().mapToDouble(o1 -> Double.valueOf(o1.get("value").toString())).sum();
        // 获取运行时长统计
        List<Map<String, Object>> runningHourDataList = this.getRunningHoursList(reqMap);
        // 补充数据
        runningHourDataList = this.processData(runningHourDataList, startTime, endTime);
        totalRunningHours = runningHourDataList.stream().mapToDouble(o1 -> Double.valueOf(o1.get("value").toString())).sum();
        // 合并数据
        int dailyFuelConsumptionListSize = dailyFuelConsumptionList.size();
        for (int i = 0; i < dailyFuelConsumptionListSize; i++) {
            dailyFuelConsumptionList.get(i).put("value2", runningHourDataList.get(i).get("value"));
        }
        Map<String, Object> resultMap = new HashMap<>(5);
        resultMap.put("list", dailyFuelConsumptionList);
        resultMap.put("totalFuelConsumption", totalFuelConsumption);
        resultMap.put("totalRunningHours", new DecimalFormat("0.0").format(totalRunningHours));
        return resultMap;

    }

    /**
     * 获取油箱容量百分比
     *
     * @param fuelGauge
     * @return
     */
    private double getFuelGaugePercentage(String fuelGauge) {
        double fuelGaugeValue = Double.valueOf(fuelGauge);
        if (fuelGaugeValue < 0) {
            fuelGaugeValue = 0;
        } else if (fuelGaugeValue > 100) {
            fuelGaugeValue = 100;
        }
        return fuelGaugeValue / 100D;
    }

    private int getTankCapacity(String thingsId){
        String tankCapacity = toolCarDataMapper.getFuelGauge(thingsId);
        return getFuelTank(tankCapacity);
    }

    /**
     * 获取油箱容量
     * @return
     */
    private int getFuelTank(Object tankCapacity) {
        //  获取油箱容量
        if (tankCapacity == null) {
            return 300;
        }
        return Integer.valueOf((String) tankCapacity);
    }

    @Override
    public Map<String, Object> carFuelConsumptionWorkHoursStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {
        // 获取时间
        LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString());
        LocalDate endTime = DateUtil.parseDate(reqMap.get("endTime").toString());
        // 判断当前用户是否是游客
        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            return carDataMocha.getCarFuelConsumptionWorkHoursStatistics(startTime, endTime);
        } else {
            // 设置服务商id
            reqMap.put("sId", currentUser.getS_id());
        }
        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
        if (pcCarMap == null || pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
        }
        String intelligentTemplateId = pcCarMap.get("device_template").toString(),
                thingsId = reqMap.get("thingsId").toString(),
                tableName = ThingsData.getTableName(intelligentTemplateId);
        // 获取油箱容量
        int tankCapacity = this.getTankCapacity(thingsId);

        // 获取每日油耗列表
        List<Map<String, Object>> fuelConsumptionList;
        // 封装数据列表
        List<Map<String, Object>> dailyFuelConsumptionList;
        // 总耗油
        double totalFuelConsumption;
        // 总工时
        double totalRunningHours;

        // 判断模版是否含有Ignition字段，如果有按照TotalFuelAmount总燃油消耗每天的差值来计算燃油消耗，负责按照燃油百分比FuelGauge来计算
        if (toolCarDataMapper.getIntelligentTemplateDetail(Constants.THINGS_Ignition, intelligentTemplateId) != null) {
            fuelConsumptionList = toolCarDataMapper.getEveryDayFuelAmount(thingsId, tableName);
            fuelConsumptionList = this.getOilConsumption(fuelConsumptionList);
        } else {
            reqMap.put("tableName", tableName);
            reqMap.put("isMax", true);
            reqMap.put("tag", FuelGauge);
            // 每个时间段开始时间油位
            List<Map<String, Object>> firstHistoryDataList = toolCarDataMapper.borderHourlyData(reqMap);
            // 每个时间段最大峰值油位
            List<Map<String, Object>> maximumHourlyPeakList = toolCarDataMapper.hourlyPeak(reqMap);
            reqMap.put("isMax", false);
            reqMap.put("tag", FuelGauge);
            // 每个时间段结束时间油位
            List<Map<String, Object>> lastHistoryDataList = toolCarDataMapper.borderHourlyData(reqMap);
            // 每个时间段最小峰值油位
            List<Map<String, Object>> minimumHourlyPeakList = toolCarDataMapper.hourlyPeak(reqMap);
            // 计算油位获取每日数据差
            fuelConsumptionList = this.getOilConsumption(maximumHourlyPeakList, minimumHourlyPeakList, firstHistoryDataList, lastHistoryDataList, tankCapacity);

        }
        dailyFuelConsumptionList = this.processData(fuelConsumptionList, startTime, endTime);
        totalFuelConsumption = dailyFuelConsumptionList.stream().mapToDouble(o1 -> Double.valueOf(o1.get("value").toString())).sum();
        // 获取运行时长统计
        List<Map<String, Object>> runningHourDataList = this.getRunningHoursList(reqMap);
        // 补充数据
        runningHourDataList = this.processData(runningHourDataList, startTime, endTime);
        totalRunningHours = runningHourDataList.stream().mapToDouble(o1 -> Double.valueOf(o1.get("value").toString())).sum();
        // 合并数据
        int dailyFuelConsumptionListSize = dailyFuelConsumptionList.size();
        for (int i = 0; i < dailyFuelConsumptionListSize; i++) {
            dailyFuelConsumptionList.get(i).put("value2", runningHourDataList.get(i).get("value"));
        }
        Map<String, Object> resultMap = new HashMap<>(5);
        resultMap.put("list", dailyFuelConsumptionList);
        resultMap.put("totalFuelConsumption", totalFuelConsumption);
        resultMap.put("totalRunningHours", new DecimalFormat("0.0").format(totalRunningHours));
        return resultMap;
    }

    @Override
    public Map<String, Object> carFuelConsumptionWorkHoursStatistics2(User currentUser, Map<String, Object> reqMap) throws MyException {
        String date = reqMap.get("date").toString();
        String yearDate = null,
                monthDate = null,
                currentMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));

        boolean isCurrentMonth = false;
        if (date.length() == 4) {
            yearDate = date;
        } else if (date.length() == 7) {
            monthDate = date;
            if (monthDate.equals(currentMonth)) {
                isCurrentMonth = true;
            }
        }
        String thingsId = reqMap.get("thingsId").toString();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("thingsId", reqMap.get("thingsId"));
        queryMap.put("yearDate", yearDate);
        queryMap.put("monthDate", monthDate);
        // value 是油耗 value2是工时
        List<Map<String, Object>> fuelConsumptionList = toolCarDataMapper.listFuelConsumption(queryMap);

        List<Map<String, Object>> dataList = new ArrayList<>();
        int distance;

        if (yearDate != null) {
            distance = 11;
            dataList = this.wrapHandle(fuelConsumptionList, distance);
        } else if (monthDate != null) {
            LocalDate startDayOfMonth = DateUtil.parseDate(monthDate + "-01");
            if (isCurrentMonth) {
                distance = Period.between(startDayOfMonth, LocalDate.now()).getDays();
            } else {
                LocalDate endDayOfMonth = startDayOfMonth.with(TemporalAdjusters.lastDayOfMonth());
                distance = Period.between(startDayOfMonth, endDayOfMonth).getDays();
            }
            dataList = this.wrapHandle(fuelConsumptionList, distance);
        }

        int workDays = 0,
                continuousWorkDays = 1;
        double avgHours = 0D,
                totalWorkHours = 0D,
                totalConsumption = 0D;

        if (monthDate != null) {
            for (Map<String, Object> fuelConsumptionMap : fuelConsumptionList) {
                if (fuelConsumptionMap.get("value2") != null) {
                    Map<String, Object> workHoursJson = JSON.parseObject(fuelConsumptionMap.get("value2").toString());
                    if (workHoursJson.get("workHours") != null) {
                        double workHours = Double.valueOf(workHoursJson.get("workHours").toString());
                        if (workHours > 0) {
                            // 工作天数
                            workDays++;
                        }
                        // 总工作小时
                        totalWorkHours += workHours;
                    }
                }
            }
        } else if (yearDate != null) {
            // 拿工时数据做工时统计
            List<Map<String, Object>> workHoursList = toolCarDataMapper.getDataStaticsByYear(thingsId, yearDate);
            Map<String, Object> thingsData = new HashMap<>();

            int size = workHoursList.size();
            for (int i = 1; i <= 12; i++) {
                String month = String.format("%02d", i);
                double monthWorkHours = 0D;
                if (size == 0) {
                    thingsData.put(month, monthWorkHours);
                    continue;
                }
                for (Map<String, Object> workHoursMap : workHoursList) {

                    if (thingsData.get(month) != null) {
                        monthWorkHours = Double.valueOf(thingsData.get(month).toString());
                    }

                    if (workHoursMap.get("sample_month").toString().equals(month)) {
                        if (workHoursMap.get("work_hours_json") != null) {
                            Map<String, Object> workHoursJson = JSON.parseObject(workHoursMap.get("work_hours_json").toString());
                            if (workHoursJson.get("workHours") != null) {
                                double workHours = Double.valueOf(workHoursJson.get("workHours").toString());
                                if (workHours > 0) {
                                    // 工作天数
                                    workDays++;
                                }
                                // 月工作小时
                                monthWorkHours += workHours;
                                // 总工作小时
                                totalWorkHours += workHours;
                            }
                        }
                    }
                    thingsData.put(month, monthWorkHours);
                }
            }
            for (Map<String, Object> data : dataList) {
                data.put("value2", thingsData.get(data.get("date").toString()));
            }
        }

        // 获取上下数据的日期差值，当差值大于1的时候视为断续
        List<Map<String, Object>> thingsList = toolCarDataMapper.getThingsDiffDays(thingsId, yearDate, monthDate);
        int size = thingsList.size();
        ArrayList<Integer> continuousWorkDaysList = new ArrayList<>();
        if (size == 0) {
            continuousWorkDays = 0;
        } else {
            for (Map<String, Object> thingsMap : thingsList) {
                if (thingsMap.get("days") != null) {
                    if (Integer.valueOf(thingsMap.get("days").toString()) > 1) {
                        continuousWorkDaysList.add(continuousWorkDays);
                        continuousWorkDays = 1;
                        continue;
                    }
                }
                continuousWorkDays++;
                if (thingsList.get(size - 1).equals(thingsMap)) {
                    continuousWorkDaysList.add(continuousWorkDays);
                    continuousWorkDays = 0;
                }
            }
        }
        Optional<Integer> optionalWorkDays = continuousWorkDaysList.stream().max(Comparator.comparingInt(Integer::intValue));
        if (optionalWorkDays.isPresent()) {
            continuousWorkDays = optionalWorkDays.get();
        }
        Optional<Double> optionalFuelConsumption = dataList.stream().map(map -> Double.valueOf(map.get("value").toString())).max(Comparator.comparingDouble(Double::intValue));
        if (optionalFuelConsumption.isPresent()) {
            totalConsumption = optionalFuelConsumption.get();
        }
        if (workDays > 0) {
            avgHours = CarDataStatisticsUtil.round(totalWorkHours / workDays, 2);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("workDays", workDays);
        resultMap.put("continuousWorkDays", continuousWorkDays);
        resultMap.put("avgHours", avgHours);
        resultMap.put("totalWorkHours", CarDataStatisticsUtil.round(totalWorkHours, 2));
        resultMap.put("totalConsumption", CarDataStatisticsUtil.round(totalConsumption, 2));
        resultMap.put("list", dataList);
        return resultMap;
    }

    private List<Map<String, Object>> wrapHandle(List<Map<String, Object>> fuelConsumptionList, int distance){
        List<Map<String, Object>> dataList = new ArrayList<>();
        int size = fuelConsumptionList.size();
        for (int i = 0; i <= distance; i++) {
            int date = i + 1;
            String iDate = String.format("%02d", date);
            if (size == 0) {
                dataList.add(createItem(iDate, 0, 0));
                continue;
            }
            for (Map<String, Object> fuelConsumption : fuelConsumptionList) {
                if (Integer.valueOf(fuelConsumption.get("date").toString()) == date) {
                    double workHours = 0D;
                    if (fuelConsumption.get("value2") != null && StringUtils.isNotBlank(fuelConsumption.get("value2").toString())) {
                        String workHoursJson = fuelConsumption.get("value2").toString();
                        JSONObject workHoursObj = JSON.parseObject(workHoursJson);
                        if (workHoursObj.get("workHours") != null) {
                            workHours = Double.valueOf(workHoursObj.get("workHours").toString());
                        }
                    }
                    dataList.add(createItem(fuelConsumption.get("date").toString(), fuelConsumption.get("value").toString(), workHours));
                    break;
                }
                if (fuelConsumption.equals(fuelConsumptionList.get(size -1))) {
                    dataList.add(createItem(iDate, 0, 0));
                }
            }
        }
        return dataList;
    }

    private Map<String, Object> createItem(String date, Object value, Object value2){
        Map<String, Object> item = new HashMap<>(4);
        item.put("date", date);
        item.put("value", value);
        item.put("value2", value2);
        return item;
    }


    private List<Map<String, Object>> getOilConsumption(List<Map<String, Object>> everyDayFuelAmountList) {
        LinkedList<Map<String, Object>> fuelList = new LinkedList<>();
        Map<String, Object> fuel;
        for (Map<String, Object> fuelAmount : everyDayFuelAmountList) {
            fuel = new HashMap<>();
            fuel.put("date", fuelAmount.get("date"));
            if (fuelAmount.get("fuelConsumption")==null){
                fuel.put("value", "0.00");
            }else{
                fuel.put("value", fuelAmount.get("fuelConsumption").toString());
            }

            fuelList.addLast(fuel);
        }
        return fuelList;

    }

    /**
     * 获取每日数据差
     * @param maximumHourlyPeakList 每小时最大峰值列表
     * @param minimumHourlyPeakList 每小时最小峰值列表
     * @param tankCapacity 油箱容量
     * @return
     */
    private List<Map<String, Object>> getOilConsumption(List<Map<String, Object>> maximumHourlyPeakList, List<Map<String, Object>> minimumHourlyPeakList, List<Map<String, Object>> firstHourlyDataList, List<Map<String, Object>> lastHourlyDataList, int tankCapacity) {
        int dataSize = maximumHourlyPeakList.size();
        if (dataSize == 0) {
            return Collections.emptyList();
        }

        // 定义上条数据的日期
        String lastDataDate = "";

        double oilDay;
        Map<String, Object> dataMap = new HashMap<>(maximumHourlyPeakList.size());

        for (int i = 0; i < dataSize; i++) {
            oilDay = 0.0D;
            Map<String, Object> maxData = maximumHourlyPeakList.get(i);
            Map<String, Object> minData = minimumHourlyPeakList.get(i);

            LocalDateTime maxValueSampleTime = DateUtil.parseTime(maxData.get("sample_time").toString().substring(0, 19));
            LocalDateTime minValueSampleTime = DateUtil.parseTime(minData.get("sample_time").toString().substring(0, 19));

            // 油位
            double maxDataFuelGauge = Double.valueOf(maxData.get(FuelGauge).toString());
            double minDataFuelGauge = Double.valueOf(minData.get(FuelGauge).toString());

            Map<String, Object> firstData = firstHourlyDataList.get(i);
            Map<String, Object> lastData = lastHourlyDataList.get(i);

            double lastDataFuelGauge = Double.valueOf(firstData.get(FuelGauge).toString());
            double firstDataFuelGauge = Double.valueOf(lastData.get(FuelGauge).toString());
            if (lastDataFuelGauge >= 100) {
                lastDataFuelGauge = 100D;
            }
            if (firstDataFuelGauge >= 100) {
                firstDataFuelGauge = 100D;
            }

            // 如果时间线为此时状态，油位上升，说明此时间段进行了加油
            if (minValueSampleTime.isBefore(maxValueSampleTime)) {
                oilDay += this.computeOilConsumption(firstDataFuelGauge, minDataFuelGauge, tankCapacity);
                oilDay += this.computeOilConsumption(maxDataFuelGauge, lastDataFuelGauge, tankCapacity);
            } else if (minValueSampleTime.isAfter(maxValueSampleTime)) {
                oilDay += this.computeOilConsumption(firstDataFuelGauge, lastDataFuelGauge, tankCapacity);
            }

            if (StringUtils.isBlank(lastDataDate) || !lastDataDate.equals(maxData.get("data_date").toString())) {
                lastDataDate = maxData.get("data_date").toString();
            }
            if (dataMap.get(lastDataDate) == null) {
                dataMap.put(lastDataDate, oilDay);
            } else {
                dataMap.put(lastDataDate, Double.valueOf(dataMap.get(lastDataDate).toString()) + oilDay);
            }
        }

        List<Map<String, Object>> dataList = new ArrayList<>((int) (maximumHourlyPeakList.size() / 0.75));
        for (String sampleTime : dataMap.keySet()) {
            Map<String, Object> data = new HashMap<>(3);
            data.put("date", sampleTime);
            data.put("value", dataMap.get(sampleTime));
            dataList.add(data);
        }
        return dataList;
    }

    /**
     * 计算油耗
     * @param startFuelGauge
     * @param endFuelGauge
     * @param tankCapacity
     * @return
     */
    private double computeOilConsumption(double startFuelGauge, double endFuelGauge, int tankCapacity){
        return tankCapacity * ((startFuelGauge - endFuelGauge) / 100.0D);
    }

    /**
     * 车辆油位统计
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String, Object> carOilLevelStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {
        // 获取时间
        LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString().substring(0, 10));
        LocalDate endTime = LocalDate.now();
        reqMap.put("endTime", DateUtil.formatDate(endTime));
        if (startTime.isAfter(endTime)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "开始时间不能小于当前时间");
        }
        if (Constants.THINGS_ID_GUEST.equals(reqMap.get("thingsId").toString())) {
            return carDataMocha.getCarOilLevelStatistics(startTime, endTime);
        }
        boolean isToday = startTime.equals(endTime);
        ThingsData thingsData = new ThingsData().setThingsId(reqMap.get("thingsId").toString());
        if (reqMap.get("cId") != null) {
            thingsData.setCId(reqMap.get("cId").toString());
        }
        thingsDataService.setPcCarData(thingsData);
        // 设置指定查询字段查询
        reqMap.put("tableName", thingsData.getTableName());
        reqMap.put("tag", Constants.THINGS_FuelGauge);
        reqMap.put("isToday", isToday);

        LinkedList<Map<String, Object>> deviceDataList = toolCarDataMapper.listCarHistoryDataSpecifyField(reqMap);
        // 开始日期之前的最新设备数据
        Map<String, Object> lastCarDataBeforeDate = toolCarDataMapper.lastCarDataBeforeDate(thingsData.getTableName(), thingsData.getThingsId(), startTime);
        String fuelGauge;
        if (lastCarDataBeforeDate == null) {
            fuelGauge = "0";
        } else {
            if (lastCarDataBeforeDate.get(Constants.THINGS_FuelGauge) != null) {
                fuelGauge = lastCarDataBeforeDate.get(Constants.THINGS_FuelGauge).toString();
            }else {

                fuelGauge = "0";
            }
        }
        // 数据处理
        LocalDateTime nowTime = LocalDateTime.now().withNano(0);
        LocalDateTime dataStartTime = DateUtil.toLocalDateTime(startTime, true);
        long distanceMinute = DateUtil.getDistanceMinute(dataStartTime, nowTime);
        long interval = 2;
        long loop = distanceMinute / interval;

        // 是否有0点数据
        List<String> dateList = deviceDataList.stream().map(map -> map.get("date").toString().substring(0, 17) + "00").collect(Collectors.toList());
        boolean hasZeroData = dateList.contains(DateUtil.formatTime(dataStartTime));

        int deviceDataListSize = deviceDataList.size();
        LinkedList<Map<String, Object>> dataMapList = new LinkedList<>();
        Map<String, Object> dataMap;
        LocalDateTime dataTime;
        Map<String, Double> dateMap = new HashMap<>((int)(dateList.size() / 0.6));

        for (Map<String, Object> deviceData : deviceDataList) {
            dateMap.put(deviceData.get("date").toString(), CarDataStatisticsUtil.correctFuelGauge(deviceData.get(Constants.THINGS_FuelGauge).toString()));
        }

        for (int i = 0; i < loop; i++) {
            dataTime = dataStartTime.plusMinutes(i * interval);
            dataMap = new HashMap<>(6);
            if (deviceDataListSize == 0 || (i == 0 && !hasZeroData)) {
                if (isToday) {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("HH:mm")));
                } else {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
                }

                if (CarDataStatisticsUtil.correctFuelGauge(fuelGauge) > 0) {

                    dataMap.put("value", CarDataStatisticsUtil.correctFuelGauge(fuelGauge));
                    dataMapList.add(dataMap);
                }

                continue;
            }
            if (!dateList.contains(DateUtil.formatTime(dataTime))) {
                if (isToday) {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("HH:mm")));
                } else {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
                }

                if (dataMapList.size() > 0) {
                    if (Double.parseDouble(dataMapList.getLast().get("value").toString()) > 0) {
                        dataMap.put("value", dataMapList.getLast().get("value"));
                        dataMapList.add(dataMap);
                    }
                }

            } else {
                if (isToday) {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("HH:mm")));
                } else {
                    dataMap.put("date", dataTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
                }
                if (dateMap.get(DateUtil.formatTime(dataTime)) > 0) {

                    dataMap.put("value", dateMap.get(DateUtil.formatTime(dataTime)));
                    dataMapList.add(dataMap);
                }
            }
        }

        // 最新的设备数据
        Map<String, Object> lastCarData = toolCarDataMapper.lastCarData(thingsData.getTableName(), thingsData.getThingsId());

        Map<String, Object> resultMap = new HashMap<>(16);
        double correctFuelGauge;
        String updateTime;
        if (lastCarData == null || lastCarData.get(Constants.THINGS_FuelGauge) == null) {
            correctFuelGauge = 0D;
            updateTime = "";
        } else {
            correctFuelGauge = CarDataStatisticsUtil.correctFuelGauge(lastCarData.get(Constants.THINGS_FuelGauge).toString());
            updateTime = lastCarData.get(Constants.THINGS_Sample_time).toString().substring(0, 19);
        }

        if (correctFuelGauge < 0) {
            correctFuelGauge = 0;
        } else if (correctFuelGauge > 100) {
            correctFuelGauge = 100;
        }

        // 如果等于零的话，找到不等于零的数据
        if (correctFuelGauge == 0) {

            String fuelGauge1 = toolCarDataMapper.getFuelGaugeRadio(thingsData.getTableName(), thingsData.getThingsId());

            correctFuelGauge = Double.valueOf(StringUtils.isBlank(fuelGauge1) ? "0" : fuelGauge1);

            if (correctFuelGauge < 0) {
                correctFuelGauge = 0;
            } else if (correctFuelGauge > 100) {
                correctFuelGauge = 100;
            }

        }
        resultMap.put("currentOilLevel", correctFuelGauge);
        resultMap.put("updateTime", updateTime);
        resultMap.put("fuelTank", CarDataStatisticsUtil.round(correctFuelGauge / 100D * getFuelTank(thingsData.getPcCarData().get("fuel_tank")), 1));

        resultMap.put("data", dataMapList);
//        resultMap.put("dataSize", dataMapList.size());
        return resultMap;
    }



    @Override
    public Map<String, Object> workingHoursDistributionStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {
        // 获取时间
        LocalDate date = DateUtil.parseDate(reqMap.get("date").toString().substring(0, 10));
        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
            //return carDataMocha.workingHoursDistributionStatistics(reqMap.get("date").toString().substring(0, 10));
        }
        ThingsData thingsData = new ThingsData().setThingsId(reqMap.get("thingsId").toString());
        //tablename未使用到，存在部分things_id不在pc_car中，故省略
        //thingsDataService.setPcCarData(thingsData);
        return this.workingHoursDistributionStatistics(thingsData.getTableName(), thingsData.getThingsId(), DateUtil.formatDate(date));
    }

    private Map<String, Object> workingHoursDistributionStatistics (String tableName, String thingsId, String date){
        String workHoursJson = toolCarDataMapper.getWorkHoursByDate(thingsId, date);
        if (workHoursJson != null) {
            return JSON.parseObject(workHoursJson);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("startTimeList", new ArrayList<>());
        resultMap.put("hours", "0.0");
        resultMap.put("endTimeList", new ArrayList<>());
        resultMap.put("workHours", "0.00");
        return resultMap;
    }

    @Override
    public Map<String, Object> getWeather(User currentUser, Map<String, Object> reqMap) throws MyException {

        String thingsId = reqMap.get("thingsId").toString();
        String date = reqMap.get("date").toString();

        ThingsData thingsData = new ThingsData().setThingsId(thingsId);
        thingsDataService.setPcCarData(thingsData);
        Map<String, Object> carData = toolCarDataMapper.lastCarDataByDate(thingsData.getTableName(), thingsData.getThingsId(), date);
        if (carData == null) {
            carData = toolCarDataMapper.lastCarData(thingsData.getTableName(), thingsData.getThingsId());
        }
        String longitude, latitude;
        if (carData == null) {
            // 经度  纬度
            longitude = "120.37151";
            latitude = "31.50363";
        } else {
            // 经度  纬度
            longitude = carData.get("GPSlongitude").toString();
            latitude = carData.get("GPSlatitude").toString();
        }
        String province = null, city = null;
        if (!(reqMap.get("province") != null && reqMap.get("city") != null)) {
            JSONObject region = addressGEOUtil.getRegion(longitude, latitude);
            province = region.get("province").toString();
            city = region.get("city").toString();
        }
        city = "[]".equals(city) ? "" : city;
        Map<String, Object> weather = weatherMapper.getWeather(province, city, date);
        if (weather == null) {
            return heFengWeather.getWeatherNow(longitude + "," + latitude);
        }
        return JSON.parseObject(weather.get("data").toString());
    }

    @Override
    public Map<String, Object> getFuelTank(User currentUser, Map<String, Object> reqMap) {
        return toolCarDataMapper.getFuelTank(reqMap);
    }

    @Override
    public void modifyFuelTank(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("update_user", currentUser.getId());
        toolCarDataMapper.modifyFuelTank(reqMap);
    }

    @Override
    public List<Map<String, Object>> processData(List<Map<String, Object>> dailyDataList, LocalDate startTime, LocalDate endTime){
        // 定义数据列表
        List<Map<String, Object>> dataMapList = new ArrayList<>();

        int length = dailyDataList.size();
        // 获取相差天数
        long days = endTime.toEpochDay() - startTime.toEpochDay();
        for (int i = 0; i <= days; i++) {
            LocalDate date1 = startTime.plusDays(i);
            Map<String, Object> data = new HashMap<>(3);
            if (length == 0) {
                data.put("date", DateUtil.formatDate(date1));
                data.put("value", "0.00");
                dataMapList.add(data);
                continue;
            }
            for (Map<String, Object> adviceData : dailyDataList) {
                LocalDate date2 = DateUtil.parseDate(adviceData.get("date").toString());
                if (date1.equals(date2)) {
                    data.put("date", DateUtil.formatDate(date1));
                    data.put("value", String.valueOf(CarDataStatisticsUtil.round(Double.valueOf(adviceData.get("value").toString()), 2)));
                    dataMapList.add(data);
                    break;
                }
                if (adviceData.equals(dailyDataList.get(length - 1))) {
                    data.put("date", DateUtil.formatDate(date1));
                    data.put("value", "0.00");
                    dataMapList.add(data);
                }
            }
        }
        // 排序 升序
        CarDataStatisticsUtil.sortASC(dataMapList);
        return dataMapList;
    }

    @Override
    public Map<String, Object> carRealFaultCode(User currentUser, Map<String, Object> reqMap) throws MyException {
//        if (isGuest(currentUser)) {
//            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
//        }
        this.appPage(reqMap);
        String thingsId = reqMap.get("thingsId").toString();

        List<Map<String, Object>> dataList = toolCarDataMapper.getFaultRealData(reqMap);

        Map<String, Object> resultMap = new HashMap<>(5);
        // 判断最新的数据是否为正常数据
        int currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        if (currentPage == 0) {
            if (dataList.size() == 0 || "2".equals(dataList.get(0).get("hi").toString())) {
                resultMap.put("currentAdviceIsOk", true);
            } else {
                resultMap.put("currentAdviceIsOk", false);
            }
        } else {
            resultMap.put("currentAdviceIsOk", null);
        }
        resultMap.put("list", dataList);
        return resultMap;
    }

    @Override
    public Map<String, Object> carHistoryFaultCode(User currentUser, Map<String, Object> reqMap) throws MyException {

        if (isGuest(currentUser)) {
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);
        }
        this.appPage(reqMap);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", toolCarDataMapper.getFaultHistoryData(reqMap));

        return resultMap;
    }

    @Override
    public List<Map<String, Object>> listForCarDateNew(User currentUser, Map<String, Object> reqMap) {
        List<Map<String, Object>> carList = new ArrayList<>();
        if (!isGuest(currentUser)) {
            reqMap.put("sId", currentUser.getS_id());
            reqMap.put("roleId", currentUser.getR_id());
            reqMap.put("userId", currentUser.getId());

            //  如果 s_id 是测试模拟客户，则临时模拟设备 - added at 2022年6月1日09:30:01
            if(currentUser.getS_id().equals(Constants.wxtkjMoNiSId)) {
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("advice_name","模拟设备");
                hashMap.put("thingsId", "17010101806");
                Map<String, Object> gps = toolCarDataMapper.getLocationRealData(hashMap);
                hashMap.put("GPSlongitude",gps.get("GPSlongitude"));
                hashMap.put("GPSlatitude",gps.get("GPSlatitude"));
                hashMap.put("GP_NUM",2);
                hashMap.put("fault_status",2);
                hashMap.put("id","867ce67fe2aa4f5eb76a19221154d410");
                hashMap.put("model","探矿装载机");
                hashMap.put("normal_img_url","8");
                hashMap.put("status",1);
                hashMap.put("things_id","17010101806");
                hashMap.put("type_img_url","8/1.png");
                carList.add(hashMap);

                return carList;
            }

            if (isSuperAdmin(currentUser.getUser_account())) {
                reqMap.put("superAdmin", true);
                carList = toolCarDataMapper.listForCarNew(reqMap);
            } else {
                //查询是否生产商  1:主机厂;2:子服务商;3:服务商;4:金融平台
                int type = toolCarDataMapper.selectIsServer(currentUser.getS_id());
                if (type == 1) {
                    List<String> arrayList = new ArrayList<>();
                    if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //查询权限
                        arrayList = toolCarDataMapper.selectSidByServer(currentUser.getId());
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //主机厂下所有服务商
                        arrayList = facilitatorPersonnelRelationDao.selectCountBySid(currentUser.getS_id());
                    }
                    String serverString = "";
                    if (arrayList.size() != 0) {
                        serverString = "'" +
                                org.apache.commons.lang3.StringUtils.join(arrayList, "','") + "'";
                        reqMap.put("serverString", serverString);
                        reqMap.put("superAdmin", true);
                        carList = toolCarDataMapper.listForCarNew(reqMap);

                        if(type == 1 && currentUser.getS_id().equals(Constants.hdznSId)) {
                            carList.forEach(car -> {
                                if(car.get("fault_status").equals(1)) {
                                    car.put("type_img_url", "10/3.png");
                                }else{
                                    if(car.get("device_status").equals(1)){
                                        if(car.get("status").equals(1)){
                                            car.put("type_img_url", "10/4.png");
                                        }else{
                                            car.put("type_img_url", "10/1.png");
                                        }
                                    }else{
                                        car.put("type_img_url", "10/2.png");
                                    }
                                }
                            });
                        }
                    } else {
                        carList = Collections.emptyList();
                    }
                    //是否是金融平台
                }else if(type == 4){
                    List<String> arrayList = new ArrayList<>();
                    if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //查询权限
                        arrayList = toolCarDataMapper.selectSidByServer(currentUser.getId());
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //主机厂下所有服务商
                        arrayList = facilitatorPersonnelRelationDao.selectCountByBankingSid(currentUser.getS_id());
                    }
                    String serverString = "";
                    if (arrayList.size() != 0) {
                        serverString = "'" +
                                org.apache.commons.lang3.StringUtils.join(arrayList, "','") + "'";
                        reqMap.put("serverString", serverString);
                        reqMap.put("superAdmin", true);
                        carList = toolCarDataMapper.listForCarNew(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                } else {
                    if (Constants.ROLE_CZ.equals(currentUser.getR_id()) || Constants.ROLE_SJ.equals(currentUser.getR_id())) {
                        carList = toolCarDataMapper.listOwnerForCarNew(reqMap);
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id())) {
                        carList = toolCarDataMapper.listForCarNew(reqMap);
                    } else if(Constants.ROLE_XS.equals(currentUser.getR_id())){
                        reqMap.put("s_id",currentUser.getS_id());
                        reqMap.put("current_logined_user_id", currentUser.getId());
                        reqMap.put("current_logined_user_r_id", currentUser.getR_id());
                        carList = toolCarDataMapper.listForCarNew(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                    //测试代码
                    /*carList.forEach(car -> {
                        if(car.get("things_id").equals("18211810167")){
                            car.put("fault_status",1);
                        }
                        if(car.get("things_id").equals("17010104550")){
                            car.put("status",1);
                            car.put("device_status",1);
                        }
                        if(car.get("things_id").equals("17010104101")){
                            car.put("status",1);
                            car.put("device_status",2);
                        }
                        if(car.get("things_id").equals("18010101022")){
                            car.put("status",2);
                        }
                        if(car.get("fault_status").equals(1)) {
                            car.put("type_img_url", "10/3.png");
                        }else{
                            if(car.get("status").equals(1)){
                                if(car.get("device_status").equals(1)){
                                    car.put("type_img_url", "10/4.png");
                                }else{
                                    car.put("type_img_url", "10/1.png");
                                }
                            }else{
                                car.put("type_img_url", "10/2.png");
                            }
                        }
                    });*/
                    if(type == 2 && tsssVehicleBrandParentDao.getPServerIdByServerId(currentUser.getS_id()).equals(Constants.hdznSId)) {
                        carList.forEach(car -> {
                            if(car.get("fault_status").equals(1)) {
                                car.put("type_img_url", "10/3.png");
                            }else{
                                if(car.get("device_status").equals(1)){
                                    if(car.get("status").equals(1)){
                                        car.put("type_img_url", "10/4.png");
                                    }else{
                                        car.put("type_img_url", "10/1.png");
                                    }
                                }else{
                                    car.put("type_img_url", "10/2.png");
                                }
                            }
                        });
                    }
                }
            }
        } else {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("advice_name","体验机");
            hashMap.put("thingsId", "18201110265");
            Map<String, Object> gps = toolCarDataMapper.getLocationRealData(hashMap);
            hashMap.put("GPSlongitude",gps.get("GPSlongitude"));
            hashMap.put("GPSlatitude",gps.get("GPSlatitude"));
//            hashMap.put("GPSlongitude",121.53899284523071);
//            hashMap.put("GPSlatitude",30.147288193845995);
            hashMap.put("GP_NUM",2);
            hashMap.put("fault_status",2);
            hashMap.put("id","d53efbeceee040dfaae053f62dd76ca3");
            hashMap.put("model","卡特彼勒992K轮式装载机");
            hashMap.put("normal_img_url","8");
            hashMap.put("status",1);
            hashMap.put("things_id","18201110265");
            hashMap.put("type_img_url","8/1.png");
            carList.add(hashMap);
        }
        return carList;
    }

    @Override
    public List<Map<String, Object>> listForCarDateNewForThird(Map<String, Object> reqMap) {
        return toolCarDataMapper.listForCarDateNewForThird(reqMap);
    }

    @Override
    public PageInfo listForCarPage(User currentUser, Map<String, Object> reqMap) {
        List<Map<String, Object>> carList = new ArrayList<>();
        if (!isGuest(currentUser)) {
            reqMap.put("sId", currentUser.getS_id());
            reqMap.put("roleId", currentUser.getR_id());
            reqMap.put("userId", currentUser.getId());
            int currentPage = Orgin.getIntValue(reqMap, "currentPage");
            int pageSize = Orgin.getIntValue(reqMap, "pageSize");

            if (isSuperAdmin(currentUser.getUser_account())) {
                reqMap.put("superAdmin", true);
                PageHelper.startPage(currentPage, pageSize);
                carList = toolCarDataMapper.listCarPage(reqMap);
            }else {
                //查询是否生产商  1:主机厂;2:子服务商;3:服务商
                int type = toolCarDataMapper.selectIsServer(currentUser.getS_id());
                if (type == 1) {
                    List<String> arrayList = new ArrayList<>();
                    if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //查询权限
                        arrayList = toolCarDataMapper.selectSidByServer(currentUser.getId());
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //主机厂下所有服务商
                        arrayList = facilitatorPersonnelRelationDao.selectCountBySid(currentUser.getS_id());
                    }
                    String serverString = "";
                    if (arrayList.size() != 0) {
                        serverString = "'" +
                                org.apache.commons.lang3.StringUtils.join(arrayList, "','") + "'";
                        reqMap.put("serverString", serverString);
                        reqMap.put("superAdmin", "1");
                        PageHelper.startPage(currentPage, pageSize);
                        carList = toolCarDataMapper.listCarPage(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                }else {
                    if (Constants.ROLE_CZ.equals(currentUser.getR_id()) || Constants.ROLE_SJ.equals(currentUser.getR_id())) {
                        PageHelper.startPage(currentPage, pageSize);
                        carList = toolCarDataMapper.listOwnerCarNewPage(reqMap);
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id())) {
                        PageHelper.startPage(currentPage, pageSize);
                        carList = toolCarDataMapper.listCarPage(reqMap);
                    } else if(Constants.ROLE_XS.equals(currentUser.getR_id())){
                        reqMap.put("s_id",currentUser.getS_id());
                        reqMap.put("current_logined_user_id", currentUser.getId());
                        reqMap.put("current_logined_user_r_id", currentUser.getR_id());
                        PageHelper.startPage(currentPage, pageSize);
                        carList = toolCarDataMapper.listCarPage(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                }
            }
        }
        // 设置状态
        return new PageInfo<>(carList);
    }

    @Override
    public List<Map<String, Object>> selectHistory(Map<String, Object> map) throws MyException,ParseException {
        List<Map<String, Object>> history = new ArrayList<>();
        String thingsId = Orgin.getString(map,"thingsId");
        String date = Orgin.getString(map,"date");
        int page = Orgin.getIntValue(map, "page")-1;
        int mapmatch = Orgin.getIntValue(map, "mapmatch");
        String[] activeProfiles = env.getActiveProfiles();
        String activeProfile = activeProfiles[0];
        if (activeProfile.equals("prod")){
            activeProfile="DIS";
        }else if (activeProfile.equals("dev")){
            activeProfile="DEV";
        }
        Map<String, Object> map1 = toolCarDataMapper.selectTrid(activeProfile+thingsId);
        Integer trid = 0;
        Integer tid = 0 ;
        if (map1!=null) {
            trid = Integer.valueOf(map1.get("trid").toString());
            tid = Integer.valueOf(map1.get("tid").toString());
            // 180的设备都开纠偏
            if (Constants.is18Or19(thingsId)) {
                mapmatch = 1;
            }
        }
        Map<String,Object> workHourJson = this.workingHoursDistributionStatistics("",thingsId,date);
        List<String> startTime = JSON.parseObject(workHourJson.get("startTimeList").toString(), List.class);
        List<String> endTime = JSON.parseObject(workHourJson.get("endTimeList").toString(), List.class);
        if (map.containsKey("type")&&Orgin.getString(map,"type").equals("1")) {
            Integer finalTrid = trid;
            Integer finalTid = tid;
            int finalMapmatch = mapmatch;
            for (int i = 6*page; i < endTime.size()&&i < 6*(page+1) ; i++){
                Map<String, Object> log = new HashMap<>();
                String a = startTime.get(i);
                String b = endTime.get(i);
                Float tractTime = Float.valueOf(b)-Float.valueOf(a);
                if (tractTime < 0) {
                    if (endTime.size() < i-1) {
                        break;
                    } else {
                        continue;
                    }
                }
                log.put("tractTime", Math.floor(tractTime)+"小时"+Math.floor(tractTime%1*60)+"分钟");
                Long aLong = (long)Math.round(Float.valueOf(a)*60*60*1000);
                Long bLong = (long)Math.round(Float.valueOf(b)*60*60*1000);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Long beginUseTime = sdf.parse(date).getTime();
                Map<String, Object> pointList = AddressGEOUtil.pointListNew(trid, tid, beginUseTime+aLong, beginUseTime+bLong,1,mapmatch);
                Integer parseObject = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
                if (parseObject==10000) {
                    Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
                    List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
                    double distance = Double.parseDouble(parseObject2.get(0).get("distance") + "") / 1000;
                    if (distance == 0) {
                        continue;
                    }
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);
                    nf.setRoundingMode(RoundingMode.UP);
                    log.put("distance", nf.format(distance));
                    log.put("speed", String.format("%.2f", distance / tractTime));
                    if (!parseObject2.get(0).containsKey("startPoint") || !parseObject2.get(0).containsKey("endPoint")) {
                        Map<String, Object> pointListNo = AddressGEOUtil.pointListNew(trid, tid, beginUseTime + aLong, beginUseTime + bLong, 1, 0);
                        Map parseObjectNo1 = JSON.parseObject(pointListNo.get("data").toString(), Map.class);
                        parseObject2 = JSON.parseObject(parseObjectNo1.get("tracks").toString(), List.class);
                    }
                    Map parseObject3 = JSON.parseObject(parseObject2.get(0).get("startPoint").toString(), Map.class);
                    Map parseObject4 = JSON.parseObject(parseObject2.get(0).get("endPoint").toString(), Map.class);
                    String locationS = parseObject3.get("location").toString();
                    log.put("locationS", locationS);
                    String gpsLoactionS = this.getAdress(locationS);
                    log.put("addressS", gpsLoactionS);
                    String locationE = parseObject4.get("location").toString();
                    log.put("locationE", locationE);
                    String gpsLoactionE = this.getAdress(locationE);
                    log.put("addressE", gpsLoactionE);
                    history.add(log);
                }
            }
        } else if(map.containsKey("type")&&Orgin.getString(map,"type").equals("2")) {
            String lastLocation = "";
            for (int i = 3*page; i < endTime.size()&&i < 3*(page+1) ; i++){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Long beginUseTime = sdf.parse(date).getTime();
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Map<String, Object> log = new HashMap<>();
                String a;
                if (i == endTime.size()-1 ) {
                    Long nowTime = new Date().getTime();
                    if (nowTime-beginUseTime < 24*60*60*1000) {
                        a = String.valueOf((nowTime - beginUseTime) / 3600000);
                    } else {
                        a = "24";
                    }
                    log.put("endPoint", true);
                } else {
                    a = startTime.get(i + 1);
                }
                String b = endTime.get(i);
                Float tractTime = Float.valueOf(a) - Float.valueOf(b);
                if (tractTime < 0) {
                    continue;
                }
                log.put("tractTime", Math.floor(tractTime)+"小时"+Math.floor(tractTime%1*60)+"分钟");
                Long aLong = (long) Math.round(Float.valueOf(a) * 60 * 60 * 1000);
                Long bLong = (long) Math.round(Float.valueOf(b) * 60 * 60 * 1000);
                Long stopTime = beginUseTime + bLong;
                Long beginTime = beginUseTime + aLong;
                String stopS = sdf2.format(new Date(stopTime));
                String stopE = sdf2.format(new Date(beginTime));

                aLong = (long) Math.round(Float.valueOf(startTime.get(i)) * 60 * 60 * 1000);

                Map<String, Object> pointList = AddressGEOUtil.pointListNew(trid, tid, beginUseTime + aLong, beginUseTime + bLong, 1, mapmatch);
                Integer parseObject = JSON.parseObject(pointList.get("errcode").toString(), Integer.class);
                if (parseObject == 10000) {
                    Map parseObject1 = JSON.parseObject(pointList.get("data").toString(), Map.class);
                    List<Map<String, Object>> parseObject2 = JSON.parseObject(parseObject1.get("tracks").toString(), List.class);
                    if (!parseObject2.get(0).containsKey("startPoint") || !parseObject2.get(0).containsKey("endPoint")) {
                        Map<String, Object> pointListNo = AddressGEOUtil.pointListNew(trid, tid, beginUseTime + aLong, beginUseTime + bLong, 1, 0);
                        Map parseObjectNo1 = JSON.parseObject(pointListNo.get("data").toString(), Map.class);
                        parseObject2 = JSON.parseObject(parseObjectNo1.get("tracks").toString(), List.class);
                    }
                    String locationS;
                    String locationE;
                    if (!parseObject2.get(0).containsKey("endPoint") || !parseObject2.get(0).containsKey("startPoint")) {
                        locationS = "";
                        locationE = lastLocation;
                    } else {
                        Map parseObject3 = JSON.parseObject(parseObject2.get(0).get("startPoint").toString(), Map.class);
                        Map parseObject4 = JSON.parseObject(parseObject2.get(0).get("endPoint").toString(), Map.class);
                        locationS = parseObject3.get("location").toString();
                        locationE = parseObject4.get("location").toString();
                    }
                    if (i == 0 ) {
                        log.put("startPoint",true);
                        log.put("locationE", locationS);
                        String gpsLoactionS = this.getAdress(locationS);
                        log.put("addressE", gpsLoactionS);
                        history.add(log);
                    } else {
                        lastLocation = locationE;
                        log.put("locationE", locationE);
                        String gpsLoactionE = this.getAdress(locationE);
                        log.put("addressS", gpsLoactionE);
                        log.put("stopS", stopS);
                        log.put("stopE", stopE);
                        history.add(log);
                    }
                }
            }
        } else {
            throw new MyException(Constants.CODE_HANDEL_FAILED,"数据请求类型存在问题，请重新选择后再请求");
        }

        return history;
    }

    @Override
    public List<Map<String, Object>> selectTrackHistory(Map<String, Object> map) {
        List<Map<String, Object>> objects = new ArrayList<>();
        String thingsId = Orgin.getString(map,"thingsId");
        Date startTimeByParam  = Orgin.getDate(map,"startTime");
        Date endTimeByParam = Orgin.getDate(map,"endTime");
        if (new Date().before(startTimeByParam)){
          //return objects;
        }
        if (!Constants.is18Or19(thingsId)){
         return objects;
        }
        String startTimeDateString = Orgin.getString(map,"startTime");
        String endTimeDateString = Orgin.getString(map,"endTime");

        Date date = Orgin.getDate(map,"date");
        if (new Date().before(date)){
            return objects;
        }
        if (!Constants.is18Or19(thingsId)){
            return objects;
        }
        String dateString = Orgin.getString(map,"date");
        int type = Orgin.getIntValue(map,"type");//1行驶,2停车
        //查询当天轨迹段
        Map<String,Object> workHourJson = this.workingHoursDistributionStatistics("",thingsId,dateString);
        List<String> startTime = JSON.parseObject(workHourJson.get("startTimeList").toString(), List.class);
        List<String> endTime = JSON.parseObject(workHourJson.get("endTimeList").toString(), List.class);
        if (startTime.size()==endTime.size()&&startTime.size()!=0){
            List<Map<String, Object>> listS = this.getList(startTime, date, thingsId);
            List<Map<String, Object>> listE = this.getList(endTime, date, thingsId);
            if (startTime.size()!=listS.size()){
                return objects;
            }
            if (type==1){
                for(int i =0;i<listS.size();i++){
                    Map<String, Object> listMap = new HashMap<>();
                    listMap.put("startTime",listS.get(i).get("sample_time"));
                    listMap.put("locationS",listS.get(i).get("location"));
                    listMap.put("addressS",listS.get(i).get("address"));
                    listMap.put("endTime",listE.get(i).get("sample_time"));
                    listMap.put("locationE",listE.get(i).get("location"));
                    listMap.put("addressE",listE.get(i).get("address"));
                    objects.add(listMap);
                };
            }
            if (type==2){//如果是停车 进行拼接
                for(int i =0;i<listS.size()-1;i++){
                    Map<String, Object> listMap = new HashMap<>();
                    listMap.put("startTime",listE.get(i).get("sample_time"));
                    listMap.put("locationS",listE.get(i).get("location"));
                    listMap.put("addressS",listE.get(i).get("address"));
                    listMap.put("endTime",listS.get(i+1).get("sample_time"));
                    listMap.put("locationE",listS.get(i+1).get("location"));
                    listMap.put("addressE",listS.get(i+1).get("address"));
                    Float tractTime = Float.valueOf(startTime.get(i+1))
                            -Float.valueOf(endTime.get(i));
                    listMap.put("tractTime", Math.floor(tractTime)+"小时"+Math.floor(tractTime%1*60)+"分钟");
                    objects.add(listMap);
                };
            }
        }
            return objects;
    }

    @Override
    public List<Map<String, Object>> selectTrackHistoryByStartDateAndEndDate(Map<String, Object> map) throws ParseException {
        List<Map<String, Object>> objects = new ArrayList<>();
        String thingsId = Orgin.getString(map,"thingsId");
        Date dateStart = Orgin.getDate(map,"startTime");
        Date dateEnd = Orgin.getDate(map,"endTime");

        List<String> dateList=DateUtils.getDays(DateUtils.localFormater.format(dateStart), DateUtils.localFormater.format(dateEnd));

        //if (startTime.size()!=listS.size()){
        //return objects;
        //}
        if(CollUtil.isNotEmpty(dateList)){
            for (String strDate:dateList) {
                if (!Constants.is18Or19(thingsId)){
                    return objects;
                }
                String dateString = strDate;
                Date date=DateUtils.localFormater.parse(strDate);
                int type = Orgin.getIntValue(map,"type");//1行驶,2停车
                //查询当天轨迹段
                Map<String,Object> workHourJson = this.workingHoursDistributionStatistics("",thingsId,dateString);
                List<String> startTime = JSON.parseObject(workHourJson.get("startTimeList").toString(), List.class);
                List<String> endTime = JSON.parseObject(workHourJson.get("endTimeList").toString(), List.class);
                if (startTime.size()==endTime.size()&&startTime.size()!=0){
                    List<Map<String, Object>> listS = this.getList(startTime, date, thingsId);
                    List<Map<String, Object>> listE = this.getList(endTime, date, thingsId);
                    if (startTime.size()!=listS.size()){
                        return objects;
                    }
                    if (type==1){
                        for(int i =0;i<listS.size();i++){
                            Map<String, Object> listMap = new HashMap<>();
                            listMap.put("startTime",listS.get(i).get("sample_time"));
                            listMap.put("locationS",listS.get(i).get("location"));
                            listMap.put("addressS",listS.get(i).get("address"));
                            listMap.put("endTime",listE.get(i).get("sample_time"));
                            listMap.put("locationE",listE.get(i).get("location"));
                            listMap.put("addressE",listE.get(i).get("address"));
                            objects.add(listMap);
                        };
                    }
                    if (type==2){//如果是停车 进行拼接
                        for(int i =0;i<listS.size()-1;i++){
                            Map<String, Object> listMap = new HashMap<>();
                            listMap.put("startTime",listE.get(i).get("sample_time"));
                            listMap.put("locationS",listE.get(i).get("location"));
                            listMap.put("addressS",listE.get(i).get("address"));
                            listMap.put("endTime",listS.get(i+1).get("sample_time"));
                            listMap.put("locationE",listS.get(i+1).get("location"));
                            listMap.put("addressE",listS.get(i+1).get("address"));
                            Float tractTime = Float.valueOf(startTime.get(i+1))
                                    -Float.valueOf(endTime.get(i));
                            listMap.put("tractTime", Math.floor(tractTime)+"小时"+Math.floor(tractTime%1*60)+"分钟");
                            objects.add(listMap);
                        };
                    }
                }


            }
        }

        //if (new Date().before(date)){
        //return objects;
        //}
        return objects;
    }




    @Override
    public Map<String, Object> addName(Map<String, Object> carList, Map<String, Object> str) {
        String name;
        int i = toolCarDataMapper.selectIsServer(Orgin.getString(str, "sid"));
        if (i == 1) {
            name = ownerDao.getServerName(str);
            carList.put("s_name", name);
        } else {
            name = toolCarDataMapper.getOwnerName(str);
            carList.put("o_name", name);
        }
        Map<String, Object> totalWorkHour = toolCarDataMapper.getTotalWorkHour(Orgin.getString(carList, "things_id"));
        if (totalWorkHour != null) {
            if (Orgin.getString(totalWorkHour, "EngineTotalHours") != null && !Orgin.getString(totalWorkHour, "EngineTotalHours").equals("") && !Orgin.getString(totalWorkHour, "EngineTotalHours").equals("0.00")) {
                carList.put("totalWorkHour", Orgin.getString(totalWorkHour, "EngineTotalHours"));
            } else {
                if (Orgin.getDouble(carList, "running") != null && !Orgin.getDouble(carList, "running").equals("")) {
                    carList.put("totalWorkHour", Orgin.getDouble(totalWorkHour, "workHour") + Orgin.getDouble(carList, "running"));
                } else {
                    carList.put("totalWorkHour", Orgin.getDouble(totalWorkHour, "workHour"));
                }
            }
        } else {
            carList.put("totalWorkHour", "0.00");
        }
        return carList;
    }

    public List<Map<String,Object>> getList(List<String> list,Date date,String thingsId){
        List<String> list1 =new ArrayList<>();
        list.forEach(item->{
            String df = new SimpleDateFormat("yyyy-MM-dd ").format(date.getTime());
            String[] split = item.split("\\.");
            String s = df + String.format("%02d", Integer.parseInt(split[0])) +":"+ String.format("%02d", Math.round(Double.parseDouble("0."+split[1]) * 60)) ;
            list1.add(s);
        });
        //查询时间对应经纬度
        String table = toolCarDataServiceImpl.selectTableByThingsIdByDate(thingsId, date);
        List<Map<String, Object>> maps = toolCarDataMapper.selectLocationByList(table+"_tb1", list1, thingsId);
        List<String> locationList = maps.stream().map(x->Orgin.getString(x,"location")).collect(Collectors.toList());
        //坐标转换
        String stringLocation = StringUtils.join(locationList.toArray(), "|");
        Map<String, Object> regeo = addressGEOUtil.regeo(stringLocation);
        JSONArray regeocodes = (JSONArray) regeo.get("regeocodes");
        for(int i =0;i<maps.size();i++){
            if(i < regeocodes.size()) {
                Map<String, Object> map = (Map<String, Object>) regeocodes.get(i);
                String formatted_address = map.get("formatted_address").toString();
                maps.get(i).put("address", formatted_address);
            }
        };
        return maps;
    }

    public List<Map<String,Object>> getListByStartTimeAndEndTime(List<String> list,String startTime,String endTime,String thingsId) throws ParseException {
        //List<String> list1 =new ArrayList<>();
        //list.forEach(item->{
            //String df = new SimpleDateFormat("yyyy-MM-dd ").format(date.getTime());
            //String[] split = item.split("\\.");
            //String s = df + String.format("%02d", Integer.parseInt(split[0])) +":"+ String.format("%02d", Math.round(Double.parseDouble("0."+split[1]) * 60)) ;
            //list1.add(s);
        //});
        //查询时间对应经纬度
        Date date=new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
        String table = toolCarDataServiceImpl.selectTableByThingsIdByDate(thingsId, date);
        List<Map<String, Object>> maps = toolCarDataMapper.selectLocationByListByStartTimeAndEndTime(table+"_tb1", startTime,endTime, thingsId);
        List<String> locationList = maps.stream().map(x->Orgin.getString(x,"location")).collect(Collectors.toList());
        //坐标转换
        String stringLocation = StringUtils.join(locationList.toArray(), "|");
        Map<String, Object> regeo = addressGEOUtil.regeo(stringLocation);
        JSONArray regeocodes = (JSONArray) regeo.get("regeocodes");
        for(int i =0;i<maps.size();i++){
            if(i < regeocodes.size()) {
                Map<String, Object> map = (Map<String, Object>) regeocodes.get(i);
                String formatted_address = map.get("formatted_address").toString();
                maps.get(i).put("address", formatted_address);
            }
        };
        return maps;
    }

    public String getAdress(String parseObject4) {
        String[] location = parseObject4.split(",");
        String longitude = location[0].toString();
        String latitude = location[1].toString();
        String gpsLoaction = addressGEOUtil.getAddress(longitude,latitude);
        return gpsLoaction;
    }

    @Override
    public List<Map<String, Object>> listCarDateNew(User currentUser, Map<String, Object> reqMap) {
        List<Map<String, Object>> carList;
        if (!isGuest(currentUser)) {
            // 设置分页
            if (reqMap.get("currentPage") != null && StringUtils.isNotBlank(reqMap.get("currentPage").toString())) {
                this.appPage(reqMap);
            }
            reqMap.put("sId", currentUser.getS_id());
            reqMap.put("roleId", currentUser.getR_id());
            reqMap.put("userId", currentUser.getId());

            if (isSuperAdmin(currentUser.getUser_account())) {

                reqMap.put("superAdmin", true);
                carList = toolCarDataMapper.listCarNew(reqMap);
            }else {
                //查询是否生产商  1:主机厂;2:子服务商;3:服务商
                int type = toolCarDataMapper.selectIsServer(currentUser.getS_id());
                if (type == 1) {
                    List<String> arrayList = new ArrayList<>();
                    if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //查询权限
                        arrayList = toolCarDataMapper.selectSidByServer(currentUser.getId());
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id())) {
                        //主机厂下所有服务商
                        arrayList = facilitatorPersonnelRelationDao.selectCountBySid(currentUser.getS_id());
                    }
                    String serverString = "";
                    if (arrayList.size() != 0) {
                        serverString = "'" +
                                org.apache.commons.lang3.StringUtils.join(arrayList, "','") + "'";
                        reqMap.put("serverString", serverString);
                        carList = toolCarDataMapper.listCarNewByServer(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                }else {
                    if (Constants.ROLE_CZ.equals(currentUser.getR_id()) || Constants.ROLE_SJ.equals(currentUser.getR_id())) {
                        carList = toolCarDataMapper.listOwnerCarNew(reqMap);
                    } else if (Constants.ROLE_GLY.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id())) {
                        carList = toolCarDataMapper.listCarNew(reqMap);
                    } else {
                        carList = Collections.emptyList();
                    }
                }
            }

        } else {
            // 设置分页
            if (reqMap.get("currentPage") != null && StringUtils.isNotBlank(reqMap.get("currentPage").toString())) {
                this.appPage(reqMap);
            }
            reqMap.put("thingsId", Constants.THINGS_ID_GUEST);

            carList = toolCarDataMapper.listGuestCar(reqMap);

            carList.forEach(item -> {

                item.put("advice_name","体验机");
                item.put("GPSlongitude","120.370814141544");
                item.put("GPSlatitude","31.503355133447");
            });
        }

        // 设置状态
        return carList;
    }

    @Override
    public void addFaultCode(Map<String, Object> carDataMap, List<Map<String, Object>> faultCodeList, List<Map<String, Object>> dataList, String no, String intelligentTemplateId, String faultId) {
        Map<String, Object> data = new HashMap<>(16);

        if (!CarDataStatisticsUtil.equalsZero(carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + no))) {
            data.put("sample_time", carDataMap.get("sample_time"));
            data.put("things_id", carDataMap.get("things_id"));
            data.put("intelligent_id", intelligentTemplateId);
            data.put("fault_id", faultId);

            data.put("spn", carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + no).toString());

            data.put("fmi", carDataMap.get(Constants.THINGS_FAULT_CODE_FMI + no).toString());
            data.put("ls", "4");
            data.put("ls_description", Constants.LsCodeEnum.getPrizeNameByNum("4"));
            data.put("hi", carDataMap.get(Constants.THINGS_FAULT_CODE_HI + no).toString());
            data.put("hi_description", Constants.HiCodeEnum.getDescriptionByCode(carDataMap.get(Constants.THINGS_FAULT_CODE_HI + no).toString()));
            data.put("oc", carDataMap.get(Constants.THINGS_FAULT_CODE_OC + no).toString());
            // 判断是是事件代码还是故障代码
            if (isEventFaultCode(carDataMap.get(Constants.THINGS_FAULT_CODE_HI + no).toString())) {
                // 如果是事件 spn指的是故障模版中的type=3
                data.put("spn_description", getDescriptionByFaultCode(faultCodeList,
                        carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + no).toString(), Constants.THINGS_FAULT_CODE_TYPE_EVENT));
                data.put("fmi_description", "");
                dataList.add(data);
            } else {
                data.put("spn_description", getDescriptionByFaultCode(faultCodeList,
                        carDataMap.get(Constants.THINGS_FAULT_CODE_SPN + no).toString(), Constants.THINGS_FAULT_CODE_TYPE_SPN));
                data.put("fmi_description", getDescriptionByFaultCode(faultCodeList,
                        carDataMap.get(Constants.THINGS_FAULT_CODE_FMI + no).toString(), Constants.THINGS_FAULT_CODE_TYPE_FMI));
                dataList.add(data);
            }
        }
    }

    private boolean isEventFaultCode(String code){
        return Constants.HiCodeEnum.HI_CODE_10.getCode().equals(code) || Constants.HiCodeEnum.HI_CODE_20.getCode().equals(code);
    }

    private String getDescriptionByFaultCode(List<Map<String, Object>> faultCodeList, String code, String faultType){
        for (Map<String, Object> faultCodeMap : faultCodeList) {
            double codeD = Double.valueOf(code);
            if (faultCodeMap.get("type").toString().equals(faultType)
                    && faultCodeMap.get("code").toString().equals(String.valueOf((int) codeD))) {
                return faultCodeMap.get("directions").toString();
            }
        }
        return "";
    }

    @Override
    public void grabHistoryFaultCode(User currentUser, Map<String, Object> reqMap) throws MyException {
        if (reqMap.get("thingsId") == null) {
            throw new MyException(Constants.CODE_NOT_FIELD, "参数错误");
        }

        String thingsId = reqMap.get("thingsId").toString();
        Map<String, Object> faultGrab = toolCarDataMapper.getFaultGrab(thingsId);
        if (faultGrab == null) {
            toolCarDataMapper.saveFaultGrab(thingsId);
        }
    }

    @Override
    public void deleteTodayHistoryFaultCode(User currentUser, Map<String, Object> reqMap) throws MyException {
        Map<String, Object> faultCodeMap = toolCarDataMapper.getFaultCodeById(reqMap.get("id").toString());
        boolean isFault;
        if (Constants.HiCodeEnum.HI_CODE_2.getCode().equals(faultCodeMap.get("hi").toString())) {
            isFault = true;
        } else {
            isFault = false;
        }
        toolCarDataMapper.deleteFaultCodeBySpnFmi(faultCodeMap.get("spn").toString(), faultCodeMap.get("fmi").toString(), isFault);
    }

    @Override
    public void saveCarAttachment(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("update_user", currentUser.getId());
        toolCarDataMapper.saveCarAttachment(reqMap);
    }

    @Override
    public Map<String, Object> getCarAttachment(User currentUser, Map<String, Object> reqMap) {
        return toolCarDataMapper.getCarAttachment(reqMap);
    }

    @Override
    public List<Map<String, Object>> carMembership(User currentUser, Map<String, Object> reqMap) {
        List<Map<String, Object>> mapList = toolCarDataMapper.carMembership(reqMap);
        List<Map<String, Object>> membershipList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            Map<String, Object> membership;
            if (map.equals(mapList.get(0))) {
                membership = new HashMap<>();
                membership.put("user_name", map.get("u_user_name"));
                membership.put("mobile_phone", map.get("u_mobile_phone"));
                membership.put("r_id", map.get("u_r_id"));
                membership.put("role", Constants.RoleEnum.getRoleName(map.get("u_r_id").toString()));
                membershipList.add(membership);
            }
            if (map.get("d_user_name") != null) {
                membership = new HashMap<>(8);
                membership.put("user_name", map.get("d_user_name"));
                membership.put("mobile_phone", map.get("d_mobile_phone"));
                membership.put("r_id", map.get("d_r_id"));
                membership.put("role", Constants.RoleEnum.getRoleName(map.get("d_r_id").toString()));
                membershipList.add(membership);
            }
        }
        return membershipList;
    }

    @Override
    public Map<String, Object> getGPSsatellite(User currentUser, Map<String, Object> reqMap) throws MyException {

        ThingsData thingsData = new ThingsData().setThingsId(reqMap.get("thingsId").toString());
        if (reqMap.get("cId") != null) {
            thingsData.setCId(reqMap.get("cId").toString());
        }
        thingsDataService.setPcCarData(thingsData);
        Map<String, Object> resultMap = new HashMap<>();

        // 最新的设备数据
        Map<String, Object> lastCarData = toolCarDataMapper.lastCarData(thingsData.getTableName(), thingsData.getThingsId());

        try {
            if (lastCarData != null) {

                if (lastCarData.containsKey("GP_NUM")) {

                    resultMap.put("GP_NUM",lastCarData.get("GP_NUM"));
                    resultMap.put("BD_NUM",lastCarData.get("BD_NUM"));
                    resultMap.put("sample_time", lastCarData.get("sample_time"));

                    ArrayList arrayList = new ArrayList();

                    Map<String,Object> SNRtempMap = new HashMap<>();
                    Map<String,Object> PRNtempMap = new HashMap<>();

                    for (String key: lastCarData.keySet()) {

                        if (key.contains("SNR")) {

                            SNRtempMap.put(key,lastCarData.get(key));
                        }

                        if (key.contains("PRN")) {

                            PRNtempMap.put(key,lastCarData.get(key));
                        }
                    }

                    arrayList.add(SNRtempMap);
                    arrayList.add(PRNtempMap);

                    resultMap.put("GP_BD_List",arrayList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMap;
    }

    @Override
    public Map<String, Object> getDashboard(User currentUser, Map<String, Object> reqMap) throws MyException {
        if (Constants.THINGS_ID_GUEST.equals(reqMap.get("thingsId").toString())) {
            return carDataMocha.getDashboard();
        }
        ThingsData thingsData = new ThingsData().setThingsId(reqMap.get("thingsId").toString());
        if (reqMap.get("cId") != null) {
            thingsData.setCId(reqMap.get("cId").toString());
        }
        thingsDataService.setPcCarData(thingsData);
        Map<String, Object> resultMap = new HashMap<>();

        // 最新的设备数据
        Map<String, Object> lastCarData = toolCarDataMapper.lastCarData(thingsData.getTableName(), thingsData.getThingsId());
        try {
            if (lastCarData != null) {
                LocalDateTime sampleTime = DateUtil.formatTimestampToTime((Timestamp) lastCarData.get("sample_time"));
                Duration duration = Duration.between(sampleTime, LocalDateTime.now());
                if (duration.toMinutes() <= 5) {
                    // 水温 -20 ~ 120
                    if (lastCarData.get(Constants.THINGS_WaterTemperature) != null) {
                        BigDecimal waterTemperature = new BigDecimal(lastCarData.get(Constants.THINGS_WaterTemperature).toString());
                        if (waterTemperature.doubleValue() < -20d) {
                            waterTemperature = new BigDecimal(-20);
                        } else if (waterTemperature.doubleValue() > 120d) {
                            waterTemperature = new BigDecimal(120d);
                        }
                        resultMap.put(Constants.THINGS_WaterTemperature, waterTemperature.toString());
                    }
                    // 发动机转速 0 ~ 7
                    if (lastCarData.get(Constants.THINGS_RotateSpeed) != null) {
                        BigDecimal rotateSpeed = new BigDecimal(lastCarData.get(Constants.THINGS_RotateSpeed).toString()).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_UP);
                        if (rotateSpeed.doubleValue() < 0d) {
                            rotateSpeed = BigDecimal.ZERO;
                        } else if (rotateSpeed.doubleValue() > 7d) {
                            rotateSpeed = new BigDecimal(7d);
                        }
                        resultMap.put(Constants.THINGS_RotateSpeed, rotateSpeed.toString());
                    }
                    // 机油压力 0 ~ 1000
                    if (lastCarData.get(Constants.THINGS_OilPressure) != null) {
                        int oilPressure = new BigDecimal(lastCarData.get(Constants.THINGS_OilPressure).toString()).intValue();
                        if (oilPressure < 0) {
                            oilPressure = 0;
                        } else if (oilPressure > 1000) {
                            oilPressure = 1000;
                        }
                        resultMap.put(Constants.THINGS_OilPressure, oilPressure);
                    }
                    // 油位 0 ~ 100
                    if (lastCarData.get(Constants.THINGS_FuelGauge) != null) {
                        int fuelGauge = new BigDecimal(lastCarData.get(Constants.THINGS_FuelGauge).toString()).intValue();
                        if (fuelGauge < 0) {
                            fuelGauge = 0;
                        } else if (fuelGauge > 100) {
                            fuelGauge = 100;
                        }
                        resultMap.put(Constants.THINGS_FuelGauge, fuelGauge);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.putIfAbsent(Constants.THINGS_WaterTemperature, 0);
        resultMap.putIfAbsent(Constants.THINGS_RotateSpeed, 0);
        resultMap.putIfAbsent(Constants.THINGS_OilPressure, 0);
        resultMap.putIfAbsent(Constants.THINGS_FuelGauge, 0);
        return resultMap;
    }

    @Override
    public void importCarLocation() {

        // 插入经纬度的方法
        /*
        List<String> list = toolCarDataMapper.selectTemplate();

        for (String template : list) {

            if (!template.equals("")) {

                String tableName = "pc_car_data_fast" + template;

                List<Map<String, Object>> listMap = toolCarDataMapper.selectCarLocation(tableName);

                for (Map<String, Object> carMap : listMap) {

                    carMap.put("thingsId",carMap.get("things_id"));

                    if (carMap.containsKey("GPSlatitude") && carMap.containsKey("GPSlongitude")) {

                        toolCarDataMapper.insertcarLocationData(carMap);
                    }else {

                        carMap.put("GPSlatitude","31.50518");
                        carMap.put("GPSlongitude","120.36617");

                        toolCarDataMapper.insertcarLocationData(carMap);
                    }
                }
            }
        }
        */

        //t_s_ss_carlocationdata


        DecimalFormat    df   = new DecimalFormat("######0.00000");

        ArrayList tempArray = new ArrayList();

        for (int i =1 ;i < 500;i++) {

            int random1 = (int)(Math.random()*9);
            int random2 = (int)(Math.random()*9);
            int random3 = (int)(Math.random()*9);
            int random4 = (int)(Math.random()*9);
            int random5 = (int)(Math.random()*9);
            int random6 = (int)(Math.random()*9);
            int random7 = (int)(Math.random()*9);
            int random8 = (int)(Math.random()*9);

            String thingsId =  "270"+random1+random2+random3+random4+random5+random6+random7+random8;

            Random random = new Random();

            //生成64-128内的随机数
            Double GPSlatitude = random.nextDouble() * (35 - 19 + 1) + 19;

            //生成64-128内的随机数
            Double GPSlongitude = random.nextDouble() * (120 - 90  + 1) + 90;

            System.out.println(thingsId + ": "+df.format(GPSlongitude) + "--" + df.format(GPSlatitude));

            Map<String,Object> tempMap = new HashMap<>();

            //生成1-2内的随机数
            int car_status = (int)(Math.random()*2+1);

            tempMap.put("thingsId",thingsId);
            tempMap.put("GPSlongitude",df.format(GPSlongitude));
            tempMap.put("GPSlatitude",df.format(GPSlatitude));
            tempMap.put("car_status",car_status);

            try {

                JSONObject region = addressGEOUtil.getRegion(GPSlongitude.toString(), GPSlatitude.toString());

//                if (!region.get("city").toString().equals("[]")) {
//
//                    tempArray.add(tempMap);
//                    toolCarDataMapper.insertcarLocationData(tempMap);
//                }

                if (region.get("province").toString().equals("湖北省")||region.get("province").toString().equals("贵州省")||region.get("province").toString().equals("江西省")) {
//甘肃 宁夏回族自治区
                    tempArray.add(tempMap);
                    toolCarDataMapper.insertcarLocationData(tempMap);
                }
//                if (region.get("province").toString().equals("山西省")  || region.get("province").toString().equals("安徽省") || region.get("province").toString().equals("湖南省")|| region.get("province").toString().equals("广东省")|| region.get("province").toString().equals("浙江省")|| region.get("province").toString().equals("江苏省")|| region.get("province").toString().equals("陕西省")|| region.get("province").toString().equals("宁夏回族自治区")|| region.get("province").toString().equals("湖北省") || region.get("province").toString().equals("江西省")) {
////甘肃 宁夏回族自治区
//                    tempArray.add(tempMap);
//                    toolCarDataMapper.insertcarLocationData(tempMap);
//                }

            } catch (Exception e) {

            }
        }

        tempArray.forEach(item -> {

            toolCarDataMapper.insertcarLocationData((Map<String, Object>)item);
        });
    }

    @Override
    public List<Map<String, Object>> selectInfoByThingsId(Map<String, Object> map)
            throws MyException, ParseException {

        String thingsId = map.get("thingsId").toString();
        String columnName = map.get("columnName").toString();
        String startTime = map.get("startTime").toString();
        String endTime = map.get("endTime").toString();
        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
        if (pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
        }
        String adviceTemplateId = pcCarMap.get("device_template").toString();
        String tableName = ThingsData.getTableName(adviceTemplateId);
        return toolCarDataMapper.selectInfoByThingsId(tableName, thingsId,
                stringConvertDate(startTime),stringConvertDate(endTime),columnName);
    }

    @Override
    public List<String> selectPcCarList(Map<String, Object> map) {
        String sId = map.get("s_id").toString();
        return toolCarDataMapper.selectPcCarList(sId);
    }

    @Override
    public List<String> selectPcCarColumnList(Map<String, Object> map) throws MyException {
        String thingsId = map.get("thingsId").toString();
        Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
        if (pcCarMap.get("device_template") == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
        }
        String adviceTemplateId = pcCarMap.get("device_template").toString();
        String tableName = ThingsData.getTableName(adviceTemplateId);
        return toolCarDataMapper.selectPcCarColumnList(tableName);
    }

    public Date stringConvertDate(String date) throws ParseException {
        //获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //使用SimpleDateFormat的parse()方法生成Date
        Date date1 = sf.parse(date);
        //打印Date
        return date1;

    }

    public List<Map<String, Object>> selectCarList(Map<String, Object> map) throws MyException {
        String thingsIds = Orgin.getString(map, "thingsIds");
        String status = Orgin.getString(map, "status");
        List<Map<String, Object>> mapList=new ArrayList<>();
        try {
            if (thingsIds!=null&&!StringUtils.isEmpty(thingsIds)){
                String decryptResult = MD5.decrypt(thingsIds.replaceAll(" ","+"));
                mapList = toolCarDataMapper.selectByIds(decryptResult);
            }
        } catch (Exception e) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "解密失败");
        }
        if (status!=null&&!StringUtils.isEmpty(status)){
            String decryptResult = MD5.decrypt(status);
            if (!decryptResult.equals("online")){
                throw new MyException(Constants.CODE_HANDEL_FAILED, "解密失败");
            }else {
                mapList = toolCarDataMapper.selectByStatus();
            }
        }
        List<Map<String, Object>> dataList1=new ArrayList<>();
        for (Map<String, Object> item : mapList) {
            String thingsId = item.get("things_id").toString();
            //查询sid
            Map<String,Object> carInfo = toolCarDataMapper.getCarInfo(thingsId);

            String table = toolCarDataServiceImpl.selectTableByThingsIdByDate(thingsId, new Date());
            //查询昨天数据
            Map<String, Object> map1 = toolCarDataMapper.selectKtblNow(table + "_tb1", thingsId);
            if (Orgin.getDoubleValue(map1,"working_time")<0.1){
                map1.put("working_time",0);
            }
            //查询最后一条数据
            Map<String, Object> map4 = toolCarDataMapper.selectKtblDayNow(table + "_tb1", thingsId);
            if(map4==null){
                throw new MyException(Constants.CODE_HANDEL_FAILED,"暂无数据");
            }
            //获取最后一条地理位置
            String longitude = Orgin.getString(map4, "longitude");
            String latitude = Orgin.getString(map4, "latitude");

            double[] doubles = GPSUtil.gps84_To_Gcj02(Double.valueOf(latitude),
                    Double.valueOf(longitude));
            map4.put("longitude",doubles[1]);
            map4.put("latitude",doubles[0]);
            String address = addressGEOUtil.getAddress(doubles[1]+"", doubles[0]+"");
            map1.put("m_location", address);
            map1.putAll(map4);
            if (Orgin.getString(carInfo,"s_id").equals(Constants.catSId)){
                dataList1.add(map1);
            }else {
                Map<String, Object> map3 = toolCarDataMapper.selectKtblTB2(table + "_tb2", thingsId);
                String workHoursJson = toolCarDataMapper.getWorkHoursToday(thingsId);
                double today=0d;
                if (workHoursJson != null) {
                    HashMap workHoursMap = JSON.parseObject(workHoursJson, new TypeReference<HashMap<String, Object>>(){});
                    today = Orgin.getDoubleValue(workHoursMap, "workHours");
                }

                //查询模拟量总工时
                double countHour = facilitatorPersonnelRelationDao.selectCountHour(thingsId);
                //车辆总工时
                String operatingHours = Orgin.getString(carInfo, "running");
                if (operatingHours!=null){
                    map1.put("source_end_time",countHour+Double.valueOf(operatingHours)+today);
                    map1.put("total_time",today);
                }
                Double jyyykg = Orgin.getDouble(map3, "JYYYKG");
                Double cddy = Orgin.getDouble(map3, "CDDY");
                String oil_pressure="未启动";
                if (jyyykg !=null&& cddy !=null){
                    if (jyyykg<3&&cddy>4){
                        oil_pressure="正常";
                    }
                    if (jyyykg>8&&cddy>4){
                        oil_pressure="异常";
                    }
                    if (cddy==0){
                        oil_pressure="未启动";
                    }
                }
                map1.put("oil_pressure",oil_pressure);//机油压力状态
                if (cddy !=null){
                    map1.put("CDDY",map3.get("CDDY"));//机油压力
                }else {
                    map1.put("CDDY",0.0);
                }
                map1.put("status", Orgin.getIntValue(item, "STATUS"));
                dataList1.add(map1);
            }

        }
        return dataList1;
    }

    @Override
    public Map<String, Object>  selectWorkHourNew(Map<String, Object> map) {
        Date startTime = Orgin.getDate(map, "startTime");
        Date endTime = Orgin.getDate(map, "endTime");
        String thingsId = Orgin.getString(map, "thingsId");
        List<String> ymd = orderServicelmpl.createYMD(startTime, endTime);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        Map<String, Object> hashMap = new LinkedHashMap<>();
        ymd.forEach(item->{
            Map<String, Object> map1 = new HashMap<>();
            map1.put("date", item);
            map1.put("workHour", "0.00");
            Map<String, Object> mapCount = toolCarDataMapper.selectWorkHourNew(item, thingsId);
            if (mapCount!=null){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String nowDate = simpleDateFormat.format(new Date());
                //是否卡特今天设备
                if (mapCount.get("s_id").toString().equals(Constants.catSId)&&nowDate.equals(item)){
                    List<Map<String, Object>> selectKateWorkDetail = toolCarDataMapper.selectKateWorkDetail(item, thingsId);
                    double EngineTotalHours=0d;
                    if (selectKateWorkDetail.size()>1){
                        EngineTotalHours=Double.valueOf(selectKateWorkDetail.get(0).get("EngineTotalHours").toString())-
                                Double.valueOf((selectKateWorkDetail.get(selectKateWorkDetail.size()-1).get("EngineTotalHours").toString()));
                        BigDecimal b = new BigDecimal(EngineTotalHours);
                        EngineTotalHours = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        map1.put("workHour",EngineTotalHours+"");
                    }
                }else {
                    map1.put("workHour",mapCount.get("work_hours"));
                }
            }
            arrayList.add(map1);
        });
        hashMap.put("list",arrayList);
        return hashMap;//
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDateHistory() {
        List<Map<String, Object>> allThingsId = toolCarDataMapper.selectAllThingsId();
        executorService.execute(() -> {
            allThingsId.parallelStream().forEach(item->{
                String te="pc_car_data_fast";
                String thingsId = item.get("things_id").toString();
                Integer deviceTemplate = Integer.valueOf(item.get("device_template").toString());
                List<Double> maps = toolCarDataMapper.seletDataByTem(thingsId, te + deviceTemplate, item);
                double EngineTotalHours=0d;
                if (maps.size()>1){
                    EngineTotalHours=maps.get(0)-(maps.get(maps.size()-1));
                    BigDecimal b = new BigDecimal(EngineTotalHours);
                    EngineTotalHours = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    toolCarDataMapper.updateStatis(item.get("id").toString(),EngineTotalHours);
                }
            });

        });
    }

    @Override
    public PageInfo selectCarFaultCode(Map<String, Object> map) throws MyException {
        String thingsIds = Orgin.getString(map, "thingsIds");
        int currentPage = Orgin.getIntValue(map, "currentPage");
        int pageSize = Orgin.getIntValue(map, "pageSize");
        List<Map<String, Object>> mapList=new ArrayList<>();
        try {
            if (thingsIds!=null&&!StringUtils.isEmpty(thingsIds)){
                String decryptResult = MD5.decrypt(thingsIds.replaceAll(" ","+"));
                PageHelper.startPage(currentPage, pageSize);
                mapList = toolCarDataMapper.selectCarFaultCode(decryptResult,map);
                mapList.forEach(item->{
                    item.put("things_id",decryptResult);
                    List<Map<String, Object>> firstNow = toolCarDataMapper.selectCarFaultCodeFirstNow(item);
                    if(firstNow.size()==0){
                        List<Map<String, Object>> maps = toolCarDataMapper.selectCarFaultCodeInfoFirst(item);
                        item.put("first_time",Orgin.getString(maps.get(0),"first_time"));
                        if (Orgin.getString(map,"date")==null){
                            item.put("sample_time",Orgin.getString(maps.get(maps.size()-1),"first_time"));
                        }
                    }else {
                        item.put("first_time",Orgin.getString(firstNow.get(0),"first_time"));
                        if (Orgin.getString(map,"date")==null) {
                            item.put("sample_time", Orgin.getString(firstNow.get(firstNow.size() - 1), "first_time"));
                        }
                    }
                });
            }
        } catch (Exception e) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "解密失败");
        }
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }


    @Override
    public Map<String, Object> selectCarFaultCodeInfo(Map<String, Object> map) throws MyException {
        String faultId = Orgin.getString(map, "fault_id");
        Map<String, Object> mapList = new HashMap<>();
        try {//
            if (faultId!=null&&!StringUtils.isEmpty(faultId)){
                String decryptResult = MD5.decrypt(faultId.replaceAll(" ","+"));
                mapList = toolCarDataMapper.selectCarFaultCodeInfo(decryptResult);
                List<Map<String, Object>> firstNow = toolCarDataMapper.selectCarFaultCodeFirstNow(mapList);
                if(firstNow.size()==0){//
                    List<Map<String, Object>> maps = toolCarDataMapper.selectCarFaultCodeInfoFirst(mapList);
                    mapList.put("first_time",Orgin.getString(maps.get(0),"first_time"));
                    if (Orgin.getString(map,"date")==null) {
                        mapList.put("sample_time", Orgin.getString(maps.get(maps.size() - 1), "first_time"));
                    }
                }else {
                    mapList.put("first_time",Orgin.getString(firstNow.get(0),"first_time"));
                    if (Orgin.getString(map,"date")==null) {
                        mapList.put("sample_time", Orgin.getString(firstNow.get(firstNow.size() - 1), "first_time"));
                    }
                }
            }
        } catch (Exception e) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "解密失败 ");
        }
        return mapList;
    }

    @Override
    public List<String> insertTer() {
        return null;
    }

    @Override
    public Map<String, Object> selectMoreDataList(Map<String, Object> map) {
        String thingsId = Orgin.getString(map, "thingsId");
        Date startTime = Orgin.getDateTime(map, "startTime");
        Date endTime = Orgin.getDateTime(map, "endTime");
        int currentPage = Orgin.getIntValue(map, "currentPage");
        int pageSize = Orgin.getIntValue(map, "pageSize");
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> hashMap = new LinkedHashMap<>();
        hashMap.put("sample_time","时间");
        Map<String, Object> hashMapUnit = new LinkedHashMap<>();
        hashMapUnit.put("sample_time","");
        StringBuffer buffer = new StringBuffer();

        // 根据thingsId获取sid
        String sid = toolCarDataMapper.selectSidByThingsId(thingsId);
        // 如果是子服务商，则查询出来父主机厂的sid
        String p_id =  tsssVehicleBrandParentDao.getPServerIdByServerId(sid);
        if(p_id != null) {
            sid = p_id;
        }

        //机型,服务商
        List<Map<String, Object>> maps = toolCarDataMapper.selectBySidModelId(thingsId);
        //机型
        List<Map<String, Object>> mapList = toolCarDataMapper.selectByModelId(thingsId);
        //默认
        List<Map<String, Object>> selectByDefault = toolCarDataMapper.selectByDefault();

        if(sid.equals(Constants.hdznSId)) { // 合锻智能登高车服务商(后期需要与t_s_ss_column_model表关联获取)
            HashMap<String, Object> mapZTKZZ1 = new HashMap<>();
            mapZTKZZ1.put("english_text", "ZTKZZ1");
            mapZTKZZ1.put("text", "状态控制1");
            maps.add(mapZTKZZ1);

            HashMap<String, Object> mapZTKZZ2 = new HashMap<>();
            mapZTKZZ2.put("english_text", "ZTKZZ2");
            mapZTKZZ2.put("text", "状态控制2");
            maps.add(mapZTKZZ2);

            HashMap<String, Object> mapKGZT1 = new HashMap<>();
            mapKGZT1.put("english_text", "KGZT1");
            mapKGZT1.put("text", "开关状态1");
            maps.add(mapKGZT1);

            HashMap<String, Object> mapKGZT2 = new HashMap<>();
            mapKGZT2.put("english_text", "KGZT2");
            mapKGZT2.put("text", "开关状态2");
            maps.add(mapKGZT2);

            HashMap<String, Object> mapSBAJZT = new HashMap<>();
            mapSBAJZT.put("english_text", "SBAJZT");
            mapSBAJZT.put("text", "手柄按键状态");
            maps.add(mapSBAJZT);

            HashMap<String, Object> mapJCCZT = new HashMap<>();
            mapJCCZT.put("english_text", "JCCZT");
            mapJCCZT.put("text", "剪叉车状态");
            maps.add(mapJCCZT);

            HashMap<String, Object> mapJCCGZ1 = new HashMap<>();
            mapJCCGZ1.put("english_text", "JCCGZ1");
            mapJCCGZ1.put("text", "剪叉车故障1");
            maps.add(mapJCCGZ1);

            HashMap<String, Object> mapJCCGZ2 = new HashMap<>();
            mapJCCGZ2.put("english_text", "JCCGZ2");
            mapJCCGZ2.put("text", "剪叉车故障2");
            maps.add(mapJCCGZ2);

            HashMap<String, Object> mapJCCGZ3 = new HashMap<>();
            mapJCCGZ3.put("english_text", "JCCGZ3");
            mapJCCGZ3.put("text", "剪叉车故障3");
            maps.add(mapJCCGZ3);

            HashMap<String, Object> mapBatVol = new HashMap<>();
            mapBatVol.put("english_text", "BatVol");
            mapBatVol.put("text", "电压");
            maps.add(mapBatVol);

            HashMap<String, Object> mapDCDL = new HashMap<>();
            mapDCDL.put("english_text", "DCDL");
            mapDCDL.put("text", "电池电量");
            maps.add(mapDCDL);

            HashMap<String, Object> mapBDJGZSJ = new HashMap<>();
            mapBDJGZSJ.put("english_text", "BDJGZSJ");
            mapBDJGZSJ.put("text", "泵电机工作时间");
            maps.add(mapBDJGZSJ);

            HashMap<String, Object> mapCDCS = new HashMap<>();
            mapCDCS.put("english_text", "CDCS");
            mapCDCS.put("text", "充电次数");
            maps.add(mapCDCS);

            HashMap<String, Object> mapCZCS = new HashMap<>();
            mapCZCS.put("english_text", "CZCS");
            mapCZCS.put("text", "超载次数");
            maps.add(mapCZCS);

            HashMap<String, Object> mapDJSD = new HashMap<>();
            mapDJSD.put("english_text", "DJSD");
            mapDJSD.put("text", "电机速度");
            maps.add(mapDJSD);

            HashMap<String, Object> mapJCCJD = new HashMap<>();
            mapJCCJD.put("english_text", "JCCJD");
            mapJCCJD.put("text", "剪叉车角度");
            maps.add(mapJCCJD);

            HashMap<String, Object> mapJCCYL = new HashMap<>();
            mapJCCYL.put("english_text", "JCCYL");
            mapJCCYL.put("text", "剪叉车压力");
            maps.add(mapJCCYL);

            HashMap<String, Object> mapJCCYGWZ = new HashMap<>();
            mapJCCYGWZ.put("english_text", "JCCYGWZ");
            mapJCCYGWZ.put("text", "剪叉车摇杆位置");
            maps.add(mapJCCYGWZ);

            HashMap<String, Object> mapLockStatus = new HashMap<>();
            mapLockStatus.put("english_text", "lockStatus");
            mapLockStatus.put("text", "锁车状态");
            maps.add(mapLockStatus);
        }

        if(maps.size() != 0) {
            maps.forEach(item -> {
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                hashMapUnit.put(item.get("english_text").toString(),
                        item.get("unit") == null ? "" : item.get("unit"));
                buffer.append(item.get("english_text").toString() + ",");
            });
        }
        if(mapList.size() != 0 && maps.size() == 0) {
            mapList.forEach(item -> {
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                hashMapUnit.put(item.get("english_text").toString(),
                        item.get("unit") == null ? "" : item.get("unit"));
                buffer.append(item.get("english_text").toString() + ",");
            });
        }
        if(selectByDefault.size() != 0 && mapList.size() == 0 && maps.size() == 0) {
            selectByDefault.forEach(item -> {
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                hashMapUnit.put(item.get("english_text").toString(),
                        item.get("unit")==null?"":item.get("unit"));
                buffer.append(item.get("english_text").toString()+",");
            });
        }

        map1.put("keyEntity", hashMap);
        map1.put("unitEntity", hashMapUnit);
        //要查询的键集合
        String keyList = buffer.substring(0, buffer.length() - 1);

        //获取表名
        String tableName = this.selectTableByThingsIdByDate(thingsId,endTime);
        int weekS = Orgin.getWeek(startTime);
        int now = Orgin.getWeek(new Date());
        List<Map<String, Object>> moreDataList=new ArrayList<>();
        Map<String, Map<String, Object>> moreDataListOfMapTemp = new HashMap<>();
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>();
        if(weekS != now) {
            //查询数据 需要跨周
            String tableNameLast = this.selectTableByThingsIdByDate(thingsId,startTime);
            //查询表是否存在
            long isExist = toolCarDataMapper.selectIsExist(tableNameLast+"_tb1");
            if(isExist != 0l) {
                PageHelper.startPage(currentPage, pageSize);
                List<String> stringList = toolCarDataMapper.selectMoreDataListWeekData(
                        thingsId, tableNameLast + "_tb1", tableNameLast + "_tb2",
                        startTime, endTime, tableName + "_tb1", tableName + "_tb2", map.get("sortMethod") != null ? map.get("sortMethod").toString() : "asc");

                for(String item : stringList) {
                    final Map<String, Object> map2 = toolCarDataMapper.selectInfoDataWeek(item, keyList, tableName + "_tb1",
                            tableName + "_tb2");
                    if (map2 != null) {
                        moreDataListOfMapTemp.put(map2.get("sample_time").toString(), map2);
                    }
                }

                for(String item : stringList) {
                    Map<String, Object> map2 = toolCarDataMapper.selectInfoDataWeek(item, keyList, tableNameLast + "_tb1",
                            tableNameLast + "_tb2");
                    if (map2 != null) {
                        moreDataListOfMapTemp.put(map2.get("sample_time").toString(), map2);
                    }
                }
                moreDataList.addAll(moreDataListOfMapTemp.values());

                if(sid.equals(Constants.hdznSId)) {
                    for(Map<String, Object> entry : moreDataList) {
                        // 合锻智能登高车服务商在数据库的值的协议转换处理
                        if(entry.containsKey("ZTKZZ1")) {
                            String ZTKZZ1Result = Constants.getZTKZZ1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("ZTKZZ1").toString()))));
                            entry.put("ZTKZZ1", ZTKZZ1Result.equals("") ? "/" : ZTKZZ1Result);
                        }
                        if(entry.containsKey("ZTKZZ2")) {
                            String ZTKZZ2Result = Constants.getZTKZZ2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("ZTKZZ2").toString()))));
                            entry.put("ZTKZZ2", ZTKZZ2Result.equals("") ? "/" : ZTKZZ2Result);
                        }
                        if(entry.containsKey("KGZT1")) {
                            String KGZT1Result = Constants.getKGZT1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("KGZT1").toString()))));
                            entry.put("KGZT1", KGZT1Result.equals("") ? "/" : KGZT1Result);
                        }
                        if(entry.containsKey("KGZT2")) {
                            String KGZT2Result = Constants.getKGZT2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("KGZT2").toString()))));
                            entry.put("KGZT2", KGZT2Result.equals("") ? "/" : KGZT2Result);
                        }
                        if(entry.containsKey("SBAJZT")) {
                            String SBAJZTResult = Constants.getSBAJZTResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("SBAJZT").toString()))));
                            entry.put("SBAJZT", SBAJZTResult.equals("") ? "/" : SBAJZTResult);
                        }
                        if(entry.containsKey("JCCZT")) {
                            String JCCZTResult = Constants.getJCCZTResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("JCCZT").toString()))));
                            entry.put("JCCZT", JCCZTResult.equals("") ? "/" : JCCZTResult);
                        }
                        if(entry.containsKey("JCCGZ1")) {
                            String JCCGZ1Result = Constants.getJCCGZ1Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("JCCGZ1").toString()))));
                            entry.put("JCCGZ1", JCCGZ1Result.equals("") ? "/" : JCCGZ1Result);
                        }
                        if(entry.containsKey("JCCGZ2")) {
                            String JCCGZ2Result = Constants.getJCCGZ2Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("JCCGZ2").toString()))));
                            entry.put("JCCGZ2", JCCGZ2Result.equals("") ? "/" : JCCGZ2Result);
                        }
                        if(entry.containsKey("JCCGZ3")) {
                            String JCCGZ3Result = Constants.getJCCGZ3Result(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("JCCGZ3").toString()))));
                            entry.put("JCCGZ3", JCCGZ3Result.equals("") ? "/" : JCCGZ3Result);
                        }
                        if(entry.containsKey("lockStatus")) {    // 如果是合锻智能登高车服务商，锁车状态需要由10进制转为二进制，从二进制里面获取0或1
                            String lockStatusResult = Constants.getLockStatusResult(InvertBinary(DecimalToBinary(Integer.parseInt(entry.get("lockStatus").toString()))));
                            entry.put("lockStatus", lockStatusResult.equals("") ? "/" : lockStatusResult);
                        }
                    }
                }

                //优化时间排序到秒 默认升序
                if(map.get("sortMethod").equals("desc")) {
                    Collections.sort(moreDataList, (o1, o2) -> {
                        Date date1 = Orgin.getDateTime(o1, "sample_time");
                        Date date2 = Orgin.getDateTime(o2, "sample_time");
                        //return date1.compareTo(date2);   //升序
                        return date2.compareTo(date1); //降序
                    });
                }else{
                    Collections.sort(moreDataList, (o1, o2) -> {
                        Date date1 = Orgin.getDateTime(o1, "sample_time");
                        Date date2 = Orgin.getDateTime(o2, "sample_time");
                        return date1.compareTo(date2);   //升序
                        //return date2.compareTo(date1); //降序
                    });
                }

                mapPageInfo = new PageInfo<>(moreDataList);
                long countL = toolCarDataMapper.selectMoreDataListWeekDataCount(
                        thingsId, tableNameLast + "_tb1", tableNameLast + "_tb2",
                        startTime, endTime, tableName + "_tb1", tableName + "_tb2");
                mapPageInfo.setTotal(countL);
            } else {
                PageHelper.startPage(currentPage, pageSize);
                moreDataList = toolCarDataMapper.selectMoreDataList(keyList,
                        thingsId, tableName + "_tb1", tableName + "_tb2",
                        startTime, endTime);
                mapPageInfo = new PageInfo<>(moreDataList);
            }
        } else {
            PageHelper.startPage(currentPage, pageSize);
            moreDataList = toolCarDataMapper.selectMoreDataList(keyList,
                    thingsId, tableName + "_tb1", tableName + "_tb2",
                    startTime, endTime);
            mapPageInfo = new PageInfo<>(moreDataList);
        }

        map1.put("data",mapPageInfo);

        return map1;
    }

    @Override
    public void selectMoreDataListExport(Map<String, Object> map, HttpServletResponse response) throws Exception {
        String thingsId = Orgin.getString(map, "thingsId");
        Date startTime = Orgin.getDateTime(map, "startTime");
        Date endTime = Orgin.getDateTime(map, "endTime");
        String thingsName = Orgin.getString(map, "thingsName");

        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        String startString = sf.format(startTime);
        String endString = sf.format(endTime);

        // 获取每一个sheet列
        List<ExcelExportEntity> excelExportEntities = getExportExcelDefine(thingsId);
        //获取表名
        String tableName = this.selectTableByThingsIdByDate(thingsId,endTime);
        int weekS = Orgin.getWeek(startTime);
        int now = Orgin.getWeek(new Date());
        List<Map<String, Object>> moreDataList=new ArrayList<>();
        if (weekS!=now){
            //查询数据 需要跨周
            String tableNameLast = this.selectTableByThingsIdByDate(thingsId,startTime);
            moreDataList.addAll(toolCarDataMapper.selectMoreDataListWeek(getKeyList(thingsId),
                    thingsId, tableNameLast + "_tb1", tableNameLast + "_tb2",
                    startTime, endTime,tableName + "_tb1",tableName + "_tb2"));
        }else {
            moreDataList = toolCarDataMapper.selectMoreDataList(getKeyList(thingsId),
                    thingsId, tableName + "_tb1", tableName + "_tb2",
                    startTime, endTime);
        }
        ExportParams exportParams = new ExportParams();
        // 指定sheet名字
        exportParams.setSheetName("历史数据导出");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, excelExportEntities, moreDataList);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(thingsName+"_"+startString+"-"+endString, "UTF-8") + ".xls");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();


    }

    @Override
    public Map<String, Object> listCarDateInfoNew(User currentUser, Map<String, Object> str) {
        return toolCarDataMapper.listCarDateInfoNew(Orgin.getString(str,"id"));
    }



    @Override
    public void addOiLevelPictureUrl(Map<String, Object> map) throws MyException {
        map.put("id", UuidUtil.get32UUID());
        Boolean aBoolean = toolCarDataMapper.addOiLevelPictureUrl(map);
        if(aBoolean = false) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "当前图片保存失败");
        }
    }

    @Override
    public List<Map<String, Object>> getOilLevelList(Map<String, Object> reqMap) {
        List<Map<String, Object>> pictureList = toolCarDataMapper.getOilLevelList(reqMap);
        return pictureList;
    }

    @Override
    public void updateOilLevelUrl(Map<String, Object> reqMap) {
        toolCarDataMapper.updateOilLevelUrl(reqMap);

    }



    private Map<String, Object> getRowData(Map<String, Object> data) {
        for (Map.Entry<String, Object> stringIntegerEntry : data.entrySet()) {
            data.put(stringIntegerEntry.getKey(), stringIntegerEntry.getValue().toString());
        }
        return data;
    }

    private List<ExcelExportEntity> getExportExcelDefine(String thingsId) throws ParseException {
        //定义表格列名,该集合存放的就是表格的列明，每个对象就是表格中的一列
        List<ExcelExportEntity> modelList = new ArrayList<>();
        //该对象就是定义列属性的对象
        ExcelExportEntity excelentity;
        modelList.add(new ExcelExportEntity("时间", "sample_time"));
        //机型,服务商
        List<Map<String, Object>> maps = toolCarDataMapper.selectBySidModelId(thingsId);
        //机型
        List<Map<String, Object>> mapList = toolCarDataMapper.selectByModelId(thingsId);
        //默认
        List<Map<String, Object>> selectByDefault = toolCarDataMapper.selectByDefault();
        if (maps.size()!=0){
            for (Map<String, Object> item : maps) {
                excelentity = new ExcelExportEntity(item.get("text").toString(), item.get("english_text").toString());
                excelentity.setWidth(10);
                excelentity.setHeight(10);
                modelList.add(excelentity);
            }
        }

        if (mapList.size()!=0&&maps.size()==0){
            for (Map<String, Object> item : mapList) {
                excelentity = new ExcelExportEntity(item.get("text").toString(), item.get("english_text").toString());
                excelentity.setWidth(10);
                excelentity.setHeight(10);
                modelList.add(excelentity);
            }
        }
        if (selectByDefault.size()!=0&&mapList.size()==0&&maps.size()==0){
            for (Map<String, Object> item : selectByDefault) {
                excelentity = new ExcelExportEntity(item.get("text").toString(), item.get("english_text").toString());
                excelentity.setWidth(10);
                excelentity.setHeight(10);
                modelList.add(excelentity);
            }
        }
        return modelList;

    }

    private String getKeyList(String thingsId){
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> hashMap = new LinkedHashMap<>();
        StringBuffer buffer = new StringBuffer();
        //机型,服务商
        List<Map<String, Object>> maps = toolCarDataMapper.selectBySidModelId(thingsId);
        //机型
        List<Map<String, Object>> mapList = toolCarDataMapper.selectByModelId(thingsId);
        //默认
        List<Map<String, Object>> selectByDefault = toolCarDataMapper.selectByDefault();
        if (maps.size()!=0){
            maps.forEach(item->{
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                buffer.append(item.get("english_text").toString()+",");
            });
        }

        if (mapList.size()!=0&&maps.size()==0){
            mapList.forEach(item->{
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                buffer.append(item.get("english_text").toString()+",");
            });
        }
        if (selectByDefault.size()!=0&&mapList.size()==0&&maps.size()==0){
            selectByDefault.forEach(item->{
                hashMap.put(item.get("english_text").toString(),item.get("text"));
                buffer.append(item.get("english_text").toString()+",");
            });
        }
        map1.put("keyEntity",hashMap);
        //要查询的键集合
        String keyList=buffer.substring(0,buffer.length()-1);
        return keyList;
    }

    @Override
    public PageInfo faultCodeList(User currentUser, Map<String, Object> reqMap) {
        String sid = currentUser.getS_id();
        List<String> sids = toolCarDataMapper.getsidList(sid);
        reqMap.get("startTime");
        if (Orgin.getString(reqMap, "startTime")!=null){
            reqMap.put("startTime",Orgin.getString(reqMap, "startTime") + " 00:00:00");
        }
        if (Orgin.getString(reqMap, "endTime")!=null){
            reqMap.put("endTime",Orgin.getString(reqMap, "endTime") + " 23:59:59");
        }
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String,Object>> faultCodeList = toolCarDataMapper.faultCodeList(reqMap,sids);
        PageInfo<Map<String,Object>> mapPageInfo = new PageInfo<>(faultCodeList);
        return mapPageInfo;
    }

    @Override
    public PageInfo carFaultCodeList(User currentUser, Map<String, Object> reqMap) {
        String sid = currentUser.getS_id();
        List<String> sids = toolCarDataMapper.getsidList(sid);
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String,Object>> carFaultCodeList = toolCarDataMapper.carFaultCodeList(reqMap,sids);
        PageInfo<Map<String,Object>> mapPageInfo = new PageInfo<>(carFaultCodeList);
        return mapPageInfo;
    }

    @Override
    public PageInfo carFaultDetailList(User currentUser, Map<String, Object> reqMap) {
        String sid = currentUser.getS_id();
        List<String> sids = toolCarDataMapper.getsidList(sid);
        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String,Object>> carFaultDetailList = toolCarDataMapper.carFaultDetailList(reqMap);
        PageInfo<Map<String,Object>> mapPageInfo = new PageInfo<>(carFaultDetailList);
        return mapPageInfo;
    }

    @Override
    public List<FaultCodeBean> exportFaultCodeList(User currentUser, Map<String, Object> reqMap) {
        String sid = currentUser.getS_id();
        List<String> sids = toolCarDataMapper.getsidList(sid);
        List<FaultCodeBean> faultCodeList = toolCarDataMapper.exportFaultCodeList(reqMap,sids);
        return faultCodeList;
    }

    @Override
    public List<Map<String, Object>> carTirepressureData(Map<String, Object> map) {
        return toolCarDataMapper.carTirepressureData(map);
    }

    @Override
    public Map<String, Object> selectWirelessDeviceData(Map<String, Object> map) {
        return toolCarDataMapper.selectWirelessDeviceData(map);
    }

    @Override
    public List<RenewalCardEntity> exportRenewalMessage(String id) {
        String extraParams = toolCarDataMapper.exportRenewalMessage(id);
        JSONObject extraParamsJSONObject= JSON.parseObject(extraParams);
        JSONObject detailObject = JSON.parseObject(extraParamsJSONObject.get(PushConstants.KEY_PUSH_RENEWAL_UPON_EXPIRATION_PC).toString());
        List<RenewalCardEntity> list = JSONArray.parseArray(detailObject.get("simList").toString(), RenewalCardEntity.class);
        return list;
    }

}
